【问题标题】:Pygame : Keyboard event not detected (Following Catalina Update Mac)Pygame:未检测到键盘事件(在 Catalina 更新 Mac 之后)
【发布时间】: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


【解决方案1】:

如果要处理键盘事件,请使用 for 循环。例如:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        break

    elif event.type == pygame.KEYDOWN:
        print(f"{event.key} key pressed")

我不确定你的代码以前是如何工作的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2014-05-03
    • 2020-03-08
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多