我正在尝试使用python和pygame运行下面的代码,我尝试了很多事情,但是我可以找到该程序检测键盘(箭头)事件的解决方案...而且我开始认为它与Mac OS的Catalina更新。在更新之前,此代码可以正常工作……我想这与Python / Terminal之间的“可访问性”以及我授予这两个应用程序的权限有关,但我找不到能够解决的确切“权限”问题...
有人有想法吗? :)
# coding=utf-8
# imports the Pygame library
import pygame
def main():
# initializes Pygame
pygame.init()
# sets the window title
pygame.display.set_caption(u'Keyboard events')
# sets the window size
pygame.display.set_mode((400, 400))
# infinite loop
while True:
# gets a single event from the event queue
# event = pygame.event.wait()
pygame.event.pump()
# if the 'close' button of the window is pressed
if event.type == pygame.QUIT:
# stops the application
break
# captures the 'KEYDOWN' and 'KEYUP' events
if event.type in (pygame.KEYDOWN, pygame.KEYUP):
# gets the key name
key_name = pygame.key.name(event.key)
# converts to uppercase the key name
key_name = key_name.upper()
# if any key is pressed
if event.type == pygame.KEYDOWN:
# prints on the console the key pressed
print("{} key pressed".format(key_name))
# if any key is released
elif event.type == pygame.KEYUP:
# prints on the console the released key
print("{} key released".format(key_name))
# finalizes Pygame
pygame.quit()
if __name__ == '__main__':
main()
pygame.event.pump()是当您不想对该事件做任何事情时的调用。如果要处理键盘事件,请使用for循环。例如:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
elif event.type == pygame.KEYDOWN:
print(f"{event.key} key pressed")
我不确定您的代码以前如何工作。