You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何获取Pygame键盘事件对象中的key属性值?

How to Access the 'key' Value from a Pygame KEYDOWN/KEYUP Event?

Hey there! Let's break this down for you. You've got this code set up to capture keyboard events:

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
        print(event)

And when pressing the up arrow key, you see output like this:

<Event(2-KeyDown {'unicode': '', 'key': 273, 'mod': 0, 'scancode': 111})>

The Simple Solution

You can access the key value in two straightforward ways:

  1. Attribute-style access (the most common and readable approach): event.key
  2. Dictionary-style access: event['key']

Modified Code Example

Here's how to adjust your code to print only the key value:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
            # Print just the numeric key value
            print(event.key)
            # Bonus: Print a human-readable key name instead of the number
            # print(pygame.key.name(event.key))

pygame.quit()

Extra Tip

That numeric value (like 273 for the up arrow) maps to a Pygame constant. If you want more readable output, use pygame.key.name(event.key)—it'll print strings like "up" instead of raw numbers, which makes debugging way easier.

内容的提问来源于stack exchange,提问作者Fredo Ovelha

火山引擎 最新活动