@win.event
def on_key_press(key, modifiers):
if key == pyglet.window.key.UP:
print("UP")
此功能只打印一次,但我想按住UP按钮时打印UP。
您需要在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()