Pygame - Keyboard Events

Pygame recognizes KEYUP and KEYDOWN events. The pygame.key module defines functions useful for handling keyboard interaction. pygame.KEYDOWN and pygame.KEYUP events are inserted in event queue when the keys are pressed and released. key attribute is an integer ID representing every key on the keyboard.

import pygame, sys
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Hello World")
while True:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
      if event.type == pygame.KEYDOWN:
         print (key, "Key is pressed")
      if event.type == pygame.KEYUP:
         print (key, "Key is released")

Run the above code and press various keys while the Pygame window is active. Following is a sample output on Python console.

q Key is pressed
q Key is released
right shift Key is released
1 Key is pressed
1 Key is released
enter Key is pressed
enter Key is released
backspace Key is pressed
backspace Key is released
x Key is pressed
x Key is released 
home Key is pressed
home Key is released
f1 Key is pressed
f1 Key is released
left Key is pressed
left Key is released
right Key is pressed
right Key is released
up Key is pressed
up Key is released
down Key is pressed
down Key is released

As we see, event.key attribute returns a unique identifier associated with each key. The arrow keys left, right, up and down are used very often in a game situation. We can right appropriate logic if a particular key press is detected.

Other useful attributes in pygame.key module are listed below −

pygame.key.get_pressed get the state of all keyboard buttons
pygame.key.get_mods determine which modifier keys are being held
pygame.key.set_repeat control how held keys are repeated
pygame.key.get_repeat see how held keys are repeated get the name of a key identifier
pygame.key.key_code get the key identifier from a key name
pygame.key.start_text_input start handling Unicode text input events
pygame.key.stop_text_input stop handling Unicode text input events
Kickstart Your Career

Get certified by completing the course

Get Started