在 Python pyglet 中按下按钮时执行某些操作

Pop*_*lor 5 python pyglet

@win.event
def on_key_press(key, modifiers):
    if key == pyglet.window.key.UP:
        print("UP")
Run Code Online (Sandbox Code Playgroud)

此功能仅打印一次 UP,但我想在按住 UP 按钮的同时打印 UP。

Tor*_*xed 2

您需要在on_key_press.
由于该函数是一次性函数,仅在触发按键 DOWN 事件时调用。并且该触发器仅从操作系统执行一次。

因此,您需要保存DOWN状态( on_key_press)并将按下的键保存在某个位置的变量中(下面,我称之为self.keys
随后,您还需要处理任何RELEASE事件,在我下面的示例中,这些事件是在on_key_release.

以下是如何将它们结合在一起:

from pyglet import *
from pyglet.gl import *

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.keys = {}

        self.alive = 1

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        self.keys[symbol] = True

    def render(self):
        self.clear()

        ## Add stuff you want to render here.
        ## Preferably in the form of a batch.

        self.flip()

    def run(self):
        while self.alive == 1:
            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

            if key.UP in self.keys:
                print('Still holding UP')
            self.render()

if __name__ == '__main__':
    x = main()
    x.run()
Run Code Online (Sandbox Code Playgroud)