Why every key on keyboard in event.type in pygame has same id as the rest of keyboard

Viewed 16

I'm trying to check if keyUp is pressed by event.loop in pygame, but when i click any other button on keyboard i get the same output with print(event.type) that every key has same id as pygame.KEYUP Here is the code:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYUP: print("key up")
2 Answers

KEYUP down does not address the "up" key. It is the event that occurs when a key is released. You must check that the event type is KEYDOWN (key pressed) and the key is K_UP:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

        if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
            print("key up")

Also see How to get keyboard input in pygame?.

Any key that gets pressed on the keyboard generates a keydown event. Any key that gets released generates a keyup event.

  • If you want to know whether the 'up arrow' key got pressed, check for keydown on the K_UP key.
  • If you want to know whether the 'up arrow' key got released, check for keyup on the K_UP key.
  • If you want to know whether the 'down arrow' key got pressed, check for keydown on the K_DOWN key.
  • If you want to know whether the 'down arrow' key got released, check for keyup on the K_DOWN key.
Related