Python Pyglet鼠标事件不调用on_draw()也不在窗口中进行更改

Aik*_*o42 6 python pyglet python-3.x

由于某种原因,尽管我的on_key_press()功能可以正常工作,但我的程序发生的任何鼠标事件都不会使窗口中的图像消失或重新出现。

我已经尝试过状态标志并声明新的图像资源,但是它不会更改窗口中的任何内容。

有没有办法使这项工作?我应该还原到以前的pyglet版本吗?如果是这样,哪个版本?

这是我的程序代码;它在测试图像可见的情况下运行,并且每按一次键或单击鼠标,图像就会消失或重新出现:

import pyglet

window = pyglet.window.Window()

image = pyglet.resource.image('test.png')
image.anchor_x = image.width // 2
image.anchor_y = image.height // 2

state = True


@window.event
def on_draw():
    print('on_draw() called')
    window.clear()
    if state:
        image.blit(window.width // 2, window.height // 2)


@window.event
def on_mouse_press(x, y, button, modifiers):
    global state, image
    if button == pyglet.window.mouse.LEFT:
        print('mouse press')
        if state:
            state = False
        else:
            state = True


@window.event
def on_key_press(symbol, modifiers):
    global state
    print('key press')
    if state:
        state = False
    else:
        state = True


pyglet.app.run()

Run Code Online (Sandbox Code Playgroud)

谢谢!

编辑:我的python版本是3.7.2,而我的pyglet版本是1.4.7,如果事实似乎在考虑...,我使用pycharm。

Aik*_*o42 3

这似乎是装饰器功能的问题。

正如 Torxed 建议的那样,不要装饰 ,而是用您自己的函数声明on_mouse_press替换 window 对象的函数:on_mouse_press

import pyglet


image = pyglet.resource.image('test.png')
image.anchor_x = image.width // 2
image.anchor_y = image.height // 2

state = True


def on_draw():
    print('on_draw() called')
    window.clear()
    if state:
        image.blit(window.width // 2, window.height // 2)


def on_mouse_press(x, y, button, modifiers):
    global state
    print('mouse pressed')
    if state:
        state = False
    else:
        state = True


window = pyglet.window.Window()
window.on_draw = on_draw
window.on_mouse_press = on_mouse_press

pyglet.app.run()

Run Code Online (Sandbox Code Playgroud)

否则,创建该对象的子类Windowon_mouse_press使用您自己的声明覆盖该函数:

import pyglet

class Window(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super().__init__(800, 600)
        self.image = pyglet.resource.image('test.png')

        self.image = pyglet.resource.image('test.png')
        self.image.anchor_x = self.image.width // 2
        self.image.anchor_y = self.image.height // 2

        self.state = True

    def on_draw(self):
        print('on_draw() called')
        window.clear()
        if self.state:
            self.image.blit(self.width // 2, self.height // 2)

    def on_mouse_press(self, x, y, button, modifiers):
        print('mouse pressed')
        if self.state:
            self.state = False
        else:
            self.state = True


window = Window()

pyglet.app.run()

Run Code Online (Sandbox Code Playgroud)