There a basically two ways:
Option 1: use pygame.key.name()
.
It's as simple as
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
print(pygame.key.name(event.key))
The advantage over using chr
is that chr
works only if the value of event.key
is between 0 and 255 (inclusive).
If you press menu, Alt Gr, Tab or LShift, pygame.key.name
will happily return menu
, alt gr
, tab
and left shift
, while chr
will crash, crash, return whitespace, and crash.
Option 2: use the unicode
attribute of the pygame.KEYDOWN
event
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
print(event.unicode)
It will get you the letter/number or an empty string when using a function key, and it will also take modifiers into account, e.g. if you hold Shift while pressing a it will return A
instead of just a
.
The pygame.KEYDOWN event has additional attributes unicode and
scancode. unicode represents a single character string that is the
fully translated character entered. This takes into account the shift
and composition keys. scancode represents the platform-specific key
code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…