'How can you print the specific key pressed to the console in Pygame?
I am stuck on this. I am trying to output the specific key pressed to the console, but at the moment all of the keys pressed output "2". Help would be greatly appreciated!
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()
Solution 1:[1]
You are printing the type of event (KEYDOWN
), so you always get the same output.
The keyboard events KEYDOWN
and KEYUP
(see pygame.event module) create a pygame.event.Event
object with additional attributes. The key that was pressed can be obtained from the key
attribute (e.g. K_RETURN
, K_a
) and the mod
attribute contains a bitset with additional modifiers (e.g. KMOD_LSHIFT
). The unicode
attribute provides the Unicode representation of the keyboard input.
A user friendly name of a key can be get by 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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |