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

2024-04-23 16:49:47 发布

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

@win.event
def on_key_press(key, modifiers):
    if key == pyglet.window.key.UP:
        print("UP")

这个函数只打印一次,但我想在按住按钮的同时打印。在


Tags: key函数eventifondefwindow按钮
1条回答
网友
1楼 · 发布于 2024-04-23 16:49:47

您需要在on_key_press之外执行此检查。
因为该函数是一个只在触发按键按下事件时调用的一次性函数。而该触发器只在操作系统中执行一次。在

所以您需要保存一个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()

相关问题 更多 >