python - 如何在 Pygame 中打印按下控制台的特定键?

标签 python pygame

我被困在这个问题上。我试图将按下的特定键输出到控制台,但目前按下的所有键都输出“2”。非常感谢您的帮助!

import pygame
pygame.init()

s = pygame.display.set_mode((640, 480))

running = True
while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT: #The user closed the window!
            running = False #Stop running
    # Logic goes here

        if e.type == pygame.KEYDOWN:
            print(e.type)

pygame.quit()

最佳答案

您正在打印事件类型 (KEYDOWN),因此您始终会得到相同的输出。

键盘事件KEYDOWNKEYUP(参见pygame.event模块)创建一个pygame.event.Event具有附加属性的对象。按下的键可以从 key 属性(例如 K_RETURN K_a)和 mod 属性获取包含带有附加修饰符的位集(例如 KMOD_LSHIFT)。 unicode 属性提供键盘输入的 Unicode 表示形式。
key 的用户友好名称可以通过 pygame.key.name() 获得:

running = True
while running:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False

        elif e.type == pygame.KEYDOWN:
            
            # print key
            print(e.key)

            # print unicode representation
            print(e.unicode)

            # print user firendly name
            print(pygame.key.name(e.key))

关于python - 如何在 Pygame 中打印按下控制台的特定键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65633964/

相关文章:

python - 改变 turtle 的外观

python - 服务器端 COLLADA 转换器

python - 使用 numpy 从图像数组的 RGB 值获取 (x,y) 坐标值

python - 当 sklearn 管道中有多种特征选择方法时,如何获取所选特征的名称?

python - Pygame 无边界打开,有一些偏移

python - 使用 google colab 时出现 NameError : name 'transforms' is not defined,

python - 更改特定文本的字体大小 - Python/Pygame

python - pygame更新不一致

python - 在显示更新之间使用 pygame.time.wait()

python - float 对象没有属性 __getitem__