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

问题描述 投票:4回答:1

由于某些原因,尽管我的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()

谢谢!

编辑:我的python版本是3.7.2,我的pyglet版本是1.4.7,如果事实似乎会影响到我,我会使用pycharm ...

python python-3.x pyglet
1个回答
1
投票

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

按照Torxed的建议,而不是装饰on_mouse_press,而是用您自己对该函数的声明替换窗口对象的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()

否则,创建Window对象的子类并使用您自己的声明覆盖on_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()

© www.soinside.com 2019 - 2024. All rights reserved.