Skip to content Skip to sidebar Skip to footer

Pygame Get Key Pressed As A String

I want to change the text in the controls screen based on the key which the user presses. how do I convert pygame.event.get() into a string that shows which key has been pressed? p

Solution 1:

The code of the pressed can be get by the event.key attribute. The unicode representation for the key can be get by the event.unicode attribute. See pygame.event module.

A unser friendly name of a key can be get by pygame.key.name():

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

        print(pygame.key.name(event.key))

Note, if you want to evaluate if a certain key is pressed, the compare event.key to the constants defined in the pygame.key module:

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            # [...]elif event.key == pygame.K_RIGHT:
            # [...]

Or store the key in a variable and use it continuously in the application loop:

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        slectedKey = event.key

if slectedKey == pygame.K_UP:
    # [...]elif slectedKey == pygame.K_DOWN:
    # [...]

If you want to evaluate if a key is is hold down, the use pygame.key.get_pressed():

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False

keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
    # [...]elif keys[pygame.K_a]:
    # [...]

Post a Comment for "Pygame Get Key Pressed As A String"