1

我有一个带有 Pyglet 窗口作为属性的主对象。Pylget 的窗口类有一个称为推送处理程序的方法,它可以让我将方法推送到事件堆栈。以下代码有效:

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() 方法似乎不起作用。

import pyglet

class Main:
    win = None
    gameItems = {}

    def __init__(self, window):
        self.win = window
        GameItem.game = self
        GameItem.win = self.win
        self.gameItems["main"] = MainMenu()
        pyglet.app.run()

    def menu(self):
        self.gameItems["main"].add()

class GameItem:
    win = None

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

class MainMenu(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(width=1024, height=768))
m.menu()

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

4

1 回答 1

0

当您调用 pyglet.app.run() 时,您进入了 pyglet 循环,并且在 pyglet 窗口关闭之前它不会返回,因此只有在 pyglet 循环结束时才会调用您的 m.menu()。如果您从 Main 中删除 pyglet.app.run 行并像这样调用它:

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

有用。

于 2013-06-08T18:52:46.680 回答