Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 41 ยท Window, Loop and Events

Keyboard and Mouse Input in Pygame

Read the keyboard and mouse in Pygame. Use key.get_pressed for smooth movement, normalize diagonal speed, track the mouse, detect hovers and clicks, and build a text input box.

You already know that input arrives as events. For games you often also want to ask a direct question: "is the left arrow down right now?" or "where is the mouse?" Pygame answers both with pygame.key and pygame.mouse. This lesson covers continuous keyboard control, normalized diagonal movement, mouse position and buttons, hover and click detection, and a text input box.

Polling the keyboard

Python
keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT]:
    player.x -= speed * dt
if keys[pygame.K_RIGHT]:
    player.x += speed * dt

get_pressed() returns an object you index with key constants. An entry is true while that key is held. Call it once per frame in the update step and read from keys as often as you like. It needs the event queue to be pumped each frame, which your normal event.get() already does.

Use polling for movement and other held actions. Use KEYDOWN events for one-shot actions (jump, shoot, pause). Doing both for the same key is a common source of double actions.

To support several layouts, accept multiple keys:

Python
left = keys[pygame.K_LEFT] or keys[pygame.K_a]
right = keys[pygame.K_RIGHT] or keys[pygame.K_d]

pygame.key.get_mods() returns a bit field of modifiers: pygame.key.get_mods() & pygame.KMOD_SHIFT is nonzero while Shift is held. pygame.key.name(pygame.K_SPACE) returns "space", handy for showing key bindings.

Try it: movement from key state

We cannot read a real keyboard here, so this stand-in fakes the get_pressed() result with a small class that is indexed the same way. The movement code is exactly what you would put in a real game, including the important fix for diagonal speed.

Python Stand-in: arrow-key movement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Moving right (20 px) and right+down (also 20 px) cover the same distance, because the diagonal direction is normalized. Without normalize(), the diagonal would be about 28 px, a well-known cheat for players. Opposite keys cancel out.

The mouse

Python
x, y = pygame.mouse.get_pos()             # position inside the window
left, middle, right = pygame.mouse.get_pressed()    # booleans for the three buttons
dx, dy = pygame.mouse.get_rel()           # movement since the last call
pygame.mouse.set_visible(False)           # hide the cursor
pygame.mouse.set_pos((400, 300))          # warp the cursor

As with the keyboard, events and polling complement each other. MOUSEBUTTONDOWN fires once per click (a button press); get_pressed()[0] is true for as long as the left button is held (dragging). event.pos in a click event is the exact click location, better than calling get_pos() later.

If you drew your game on a scaled surface, convert the mouse position to game coordinates first (see The Window and Display).

Hover and click with Rects

The Rect class has collidepoint, which makes hit testing simple:

Python
button = pygame.Rect(300, 200, 200, 60)

mouse = pygame.mouse.get_pos()
hovering = button.collidepoint(mouse)
color = (90, 160, 255) if hovering else (60, 110, 200)

for event in events:
    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and button.collidepoint(event.pos):
        start_game()

Try it: hit testing

Mouse positions are just tuples, so this runs without a mouse. We test several points against a button and a draggable-handle area, and show the offset trick used for dragging.

Python Hover, click and drag offsets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Without the offset the box would jump so its corner sits under the cursor. With it, the box moves smoothly from wherever the player grabbed it.

A text input box

For typing names or chat, use events, not polling. Modern Pygame sends TEXTINPUT events with the typed text (this handles shift, accents and other keyboard layouts), and you handle Backspace and Enter from KEYDOWN. To receive text events in a real game you can call pygame.key.start_text_input() and stop with stop_text_input().

Python A text box you can test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real game you also draw the text with a font and a blinking cursor; drawing text is covered in Text and Fonts.

Controlling the cursor and grabbing input

For first-person style games you can hide the cursor and keep it inside the window with pygame.event.set_grab(True). Always provide a way to release it (usually Escape), or players cannot leave the window.

Common mistakes

  • Using KEYDOWN for movement, which gives one step per press, not smooth motion.
  • Moving diagonally faster than straight: normalize the direction vector.
  • Calling get_pressed() once at start-up instead of every frame.
  • Using event.unicode for game controls: arrows and function keys have an empty string.
  • Forgetting event.pos and reading get_pos() after the fact.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When should you use pygame.key.get_pressed() instead of KEYDOWN events?

    Polling tells you the current state each frame, which gives smooth continuous movement.
  2. 2. Why normalize the direction vector in movement code?

    Moving (1, 1) has length about 1.41. Normalizing makes every direction the same length.
  3. 3. Which call gives the exact position of a click?

    A click event carries pos, the location at the time of the click.
  4. 4. Which method checks whether a mouse position is inside a button Rect?

    collidepoint returns True when the point lies inside the rectangle.

Summary

  • Poll key.get_pressed() for held keys; use events for one-shot actions.
  • Normalize a direction Vector2 so diagonals are not faster.
  • mouse.get_pos(), get_pressed() and get_rel() poll the mouse; click events carry pos and button.
  • Rect.collidepoint handles hover and click tests; remember an offset for dragging.
  • Text input uses TEXTINPUT for characters and KEYDOWN for Backspace and Enter.

Next: Surfaces and Blitting