如何使用Pyg将另一个对象的处理程序添加到窗口中

2024-10-17 06:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以Pyglet窗口作为属性的主对象。Pylget的window类有一个名为push handlers的方法,它允许我将方法推送到事件堆栈中。以下代码有效:

import pyglet

class main:
    win = None
    gameItems = {}

    def __init__(self, window):
        self.win = window
        gameItem.win = self.win
        self.gameItems["menu"] = menu()
        self.gameItems["menu"].add()
        pyglet.app.run()

class gameItem:
    win = None

    def add(self):
        self.win.push_handlers(self)

class menu(gameItem): ##I actually have multiple objects inheriting from gameItem, this is just one of them.
    def on_mouse_press(self, x, y, button, modifier):
        '''on_mouse_press() is an accepted handler for the window object.'''
        print(x)
        print(y)

    def on_draw(self):
        '''With a quick draw function, so I can see immediately
        that the handlers are getting pushed.'''
        pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2i', (256,350,772,350,772,450,256,450)))

m = main(pyglet.window.Window())

上面的代码将以默认大小生成一个新窗口,并将on_mouse_press()和on_draw事件处理程序附加到该窗口。这很好,但是,尝试在其他类中调用push_handlers()方法似乎不起作用。在

^{pr2}$

上面的代码生成了一个新窗口,但是它没有附加菜单类的处理程序。这是有原因的吗,还是我可以利用的变通办法?谢谢!在


Tags: 方法selfonhandlersdefwindowpushwin
1条回答
网友
1楼 · 发布于 2024-10-17 06:30:06

当你打电话的时候pyglet.app.run(),则进入pyglet循环,它在pyglet窗口关闭之前不会返回,因此只有在pyglet循环结束时才会调用m.menu()。如果您移除pyglet.app.run从主管道开始,然后这样称呼它:

m = Main(pyglet.window.Window(width=1024, height=768))
m.menu()
pyglet.app.run()
print "Window is closed now."

它起作用了。在

相关问题 更多 >