Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 41 ยท Window, Loop and Events

Event Handling in Pygame

Understand the Pygame event queue. Read events with event.get, check event.type, handle key, mouse, wheel and window events, and organize handlers with a dispatch table.

Everything the player does reaches your game as an event: pressing a key, moving the mouse, clicking, resizing the window, closing it. Pygame collects events in a queue, and your loop empties that queue every frame. Understanding events well is the difference between a game that feels responsive and one that misses clicks. This lesson explains the queue, the main event types and good patterns for handling them.

The event queue

Python
for event in pygame.event.get():
    print(event)

pygame.event.get() removes all waiting events from the queue and returns them as a list, oldest first. Each element is a pygame.event.Event with a type and some attributes that depend on the type. Printing one gives you a readable summary such as <Event(768-KeyDown {'unicode': 'a', 'key': 97, 'mod': 0, 'scancode': 4})>.

Other ways to read the queue:

Function Behavior
pygame.event.get() Returns and clears all events (optionally only given types)
pygame.event.poll() Returns one event, or a NOEVENT placeholder if empty
pygame.event.wait() Blocks until an event arrives (useful for turn-based tools, not for real-time games)
pygame.event.pump() Processes internal messages without returning events; keeps the window alive if you use key.get_pressed() only
pygame.event.clear() Throws all events away
pygame.event.peek(type) True if an event of that type is waiting, without removing it
pygame.event.post(event) Adds an event of your own

Warning: Call pygame.event.get() only once per frame and share the result. If two parts of your code each call it, the first one steals all events and the second sees nothing.

The most important event types

Event Useful attributes When
QUIT none The window close button was pressed
KEYDOWN key, unicode, mod A key went down (once per press, plus key repeat if enabled)
KEYUP key, mod A key was released
MOUSEBUTTONDOWN pos, button A mouse button went down (1 left, 2 middle, 3 right)
MOUSEBUTTONUP pos, button A mouse button was released
MOUSEMOTION pos, rel, buttons The mouse moved
MOUSEWHEEL x, y The wheel scrolled
WINDOWRESIZED, VIDEORESIZE x, y or w, h The window changed size
TEXTINPUT text The player typed text (handles keyboard layouts and accents)
JOYBUTTONDOWN, JOYAXISMOTION joy, button, axis, value Gamepad input
Python
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_ESCAPE:
            running = False
        elif event.key == pygame.K_SPACE:
            player.jump()
    elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
        print("left click at", event.pos)

Key constants are named K_ plus the key: K_a to K_z, K_0 to K_9, K_SPACE, K_RETURN, K_ESCAPE, K_LEFT, K_RIGHT, K_UP, K_DOWN, K_LSHIFT, K_F1. Keyboard polling and the mouse are covered further in Keyboard and Mouse Input.

Events versus polling

Events tell you that something happened (a key went down). Polling tells you the current state (is the key down right now?). Use events for one-shot actions: jump, shoot once, open the menu, click a button. Use polling for continuous actions: walking while an arrow key is held.

Try it: inspect events

Events can be created and examined without a window. This shows how types and attributes work and how to look up a readable name for a type.

Python Create and inspect events

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.

Notice that event.dict holds all the attributes, and event.type is just an integer that you compare with constants like pygame.QUIT.

Try it: a dispatch table

Long if/elif chains get messy as the game grows. A cleaner pattern maps event types to handler functions. This stand-in runs a scripted session through one.

Python Event dispatch table

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.

Unhandled event types simply fall through get() and are ignored, which keeps the dispatcher short. When you move to classes and game states, each state will own its own handle_event method.

Event details worth knowing

  • Key repeat: by default holding a key sends one KEYDOWN. Call pygame.key.set_repeat(delay, interval) to get repeats, useful in menus and text fields.
  • event.unicode is the character typed (including shift and layout). Use it for text, never for game controls, because it is empty for keys such as arrows.
  • Modifiers: event.mod & pygame.KMOD_SHIFT tells you whether Shift was held.
  • Mouse buttons: 1 left, 2 middle, 3 right; the wheel appears as MOUSEWHEEL events (older code used buttons 4 and 5).
  • Window events: WINDOWFOCUSLOST is a good moment to pause the game automatically.
  • Filtering: pygame.event.set_blocked(pygame.MOUSEMOTION) stops a type from entering the queue at all, which helps when you do not need it.

Common mistakes

  • Reading a key with event.key == pygame.K_a in a MOUSEBUTTONDOWN branch: only some event types have key. Check event.type first.
  • Calling event.get() twice per frame.
  • Using KEYDOWN for walking: movement stops being smooth. Use polling.
  • Forgetting event.button and treating any click as a left click.
  • Checking event.type == pygame.K_SPACE: that compares a type with a key code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does pygame.event.get() do?

    It empties the queue and returns every event as a list.
  2. 2. Why should you call event.get() only once per frame?

    Events are removed when read, so a second call sees nothing. Read once and pass the list around.
  3. 3. Which attribute tells you which mouse button was pressed?

    MOUSEBUTTONDOWN has button (1, 2 or 3) and pos. buttons belongs to MOUSEMOTION.
  4. 4. Which is better for walking while an arrow key is held?

    Events fire once per press. Polling gives the current key state every frame.
  5. 5. What does a dispatch table map?

    A dictionary from event.type to a function replaces long if/elif chains.

Summary

  • Pygame queues events; pygame.event.get() returns and clears them, once per frame.
  • Compare event.type with constants like QUIT, KEYDOWN, MOUSEBUTTONDOWN.
  • Events report that something happened; polling reports the current state.
  • unicode is for text, key is for controls.
  • A dictionary of handlers keeps event code tidy.

Next: Custom Events and Timers