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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:45:45