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()
您需要在
on_key_press
之外执行此检查。因为该函数是一个只在触发按键按下事件时调用的一次性函数。而该触发器只在操作系统中执行一次。在
所以您需要保存一个
DOWN
状态(on_key_press
)并将按下的键保存在某个变量中,其中(下面,我将其称为self.keys
)随后,您还需要处理任何
RELEASE
事件,在下面的示例中,这些事件是在on_key_release
中完成的。在以下是如何将它们结合在一起的:
相关问题 更多 >
编程相关推荐