【发布时间】:2020-06-22 13:21:50
【问题描述】:
我正在尝试使用 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()
【问题讨论】:
-
你从来没有定义过
event,所以这个程序会因为NameError而崩溃。你确定这是正确的代码吗?
标签: python pygame keyboard keyboard-events macos-catalina