Keyboard input

Pygame gives you two ways to read the keyboard. Events tell you a key was pressed; get_pressed() tells you which keys are held right now. Games usually need both.

Beginner3 min readUpdated
On this page

What you'll learn

  • The difference between key events and key state
  • Smooth, diagonal movement with pygame.key.get_pressed()
  • One-shot actions such as jumping with KEYDOWN
  • Key constants, modifier keys and key names

Prerequisites: The game loop.

Two ways to read keys#

Events arrive once per press. When a key goes down you get one pygame.KEYDOWN event, and when it comes back up, one pygame.KEYUP. Use events for actions that should happen once: jumping, firing a single shot, opening a menu, pausing.

Key state comes from pygame.key.get_pressed(), which returns a sequence you can index with key constants. keys[pygame.K_LEFT] is true for every frame the key is held. Use it for continuous actions: walking, steering, holding a thruster.

Using the wrong one is the most common keyboard bug. Movement written with KEYDOWN moves once per press and feels stuck; a jump written with get_pressed() repeats every frame the key is held.

A complete example#

keyboard_input.pyDownload
"""Two ways to read the keyboard: events for single presses, get_pressed() for held keys."""
import pygame

WIDTH, HEIGHT = 640, 480
SPEED = 260
GRAVITY = 1400
JUMP = -560

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 26)

player = pygame.Rect(300, 380, 40, 40)
pos = pygame.Vector2(player.topleft)
vel_y = 0.0
on_ground = True
log = []

running = True
while running:
    dt = clock.tick(60) / 1000
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            log.append(pygame.key.name(event.key))       # one entry per press
            if event.key == pygame.K_SPACE and on_ground:
                vel_y = JUMP                               # jump happens once per press
                on_ground = False
            elif event.key == pygame.K_ESCAPE:
                running = False

    keys = pygame.key.get_pressed()                        # state of every key right now
    if keys[pygame.K_LEFT] or keys[pygame.K_a]:
        pos.x -= SPEED * dt
    if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
        pos.x += SPEED * dt
    pos.x = max(0, min(WIDTH - player.width, pos.x))

    vel_y += GRAVITY * dt
    pos.y += vel_y * dt
    if pos.y >= 380:
        pos.y, vel_y, on_ground = 380, 0.0, True
    player.topleft = (round(pos.x), round(pos.y))

    screen.fill((20, 26, 46))
    pygame.draw.rect(screen, (60, 80, 120), (0, 420, WIDTH, 60))
    pygame.draw.rect(screen, (91, 147, 230), player, border_radius=6)
    screen.blit(font.render("Left/Right or A/D to move, Space to jump, Esc to quit", True, (230, 236, 247)), (16, 16))
    screen.blit(font.render("Last keys: " + " ".join(log[-8:]), True, (244, 197, 49)), (16, 44))
    pygame.display.flip()

pygame.quit()
A blue square on a floor with the list of recently pressed keys
keyboard_input.py

The left and right movement reads get_pressed() every frame and multiplies by dt, so holding a key moves smoothly. The jump happens inside the event loop on KEYDOWN, and only when the player is on the ground, so holding Space doesn't make you fly.

Key constants and names#

Every key has a constant: pygame.K_a to pygame.K_z, pygame.K_0 to pygame.K_9, pygame.K_SPACE, pygame.K_RETURN, pygame.K_ESCAPE, pygame.K_LSHIFT, the arrow keys pygame.K_UP and so on. pygame.key.name(event.key) turns a constant into a readable name such as "space" or "left shift", which is handy for debugging and for showing key bindings in a settings menu.

event.unicode on a KEYDOWN event holds the character typed, taking Shift and the keyboard layout into account. For real text entry, such as typing a player name, use TEXTINPUT events instead. See building a text input box.

Modifier keys#

Check Ctrl, Shift and Alt with the mod attribute of a key event:

Python
if event.type == pygame.KEYDOWN and event.key == pygame.K_s and event.mod & pygame.KMOD_CTRL:
    save_game()

pygame.key.get_mods() returns the same flags at any time.

Diagonal movement at the same speed#

Pressing right and down together moves 1 pixel right and 1 down, which is about 1.41 pixels diagonally, so diagonals are faster. Normalise the direction vector to fix this:

Python
direction = pygame.Vector2(keys[pygame.K_RIGHT] - keys[pygame.K_LEFT],
                           keys[pygame.K_DOWN] - keys[pygame.K_UP])
if direction.length_squared() > 0:
    direction = direction.normalize()
pos += direction * SPEED * dt

Key repeat#

By default holding a key produces a single KEYDOWN. pygame.key.set_repeat(300, 50) makes Pygame send repeated KEYDOWN events after 300 ms, then every 50 ms, which suits menus and text fields. Call pygame.key.set_repeat() with no arguments to turn it off.

Common mistakes#

  • Reading get_pressed() inside the event loop: it then only runs on frames that have events, so movement stutters. Read it once per frame outside the loop.
  • Comparing event.key on non-key events: mouse events have no key attribute. Always check event.type == pygame.KEYDOWN first.
  • Missing keys when the window lacks focus: keyboard input only reaches the focused window. In Pygame Online, click the game area first.
  • Some key combinations don't register: many keyboards can't report certain three-key combinations ("ghosting"). Offer alternative bindings such as WASD and the arrow keys.

Practice exercises#

  1. Add a "dash": pressing Left Shift doubles the speed for 0.3 seconds, with a 1-second cooldown.
  2. Make the square change colour each time you press C.
  3. Let the player rebind the jump key: press J, then the next key pressed becomes the jump key.
  4. Show a pause overlay when P is pressed, and freeze the update phase while paused.
↑ ↓ to moveEnter to openEsc to close