pygame.event

Everything the player does, along with window changes and timers, arrives through one event queue. Learn how to read it, filter it and post your own events.

2 min readUpdated
On this page

Overview#

Pygame stores input and system messages in a queue. Each item is an Event object with a type and attributes that depend on the type. Your game loop empties the queue every frame, usually with pygame.event.get(). Reading the queue also keeps the window responsive, because it lets Pygame talk to the operating system.

Syntax#

Python
for event in pygame.event.get():       # remove and return all events
    ...
event = pygame.event.poll()            # one event, or an event of type NOEVENT
event = pygame.event.wait(timeout=0)   # sleep until an event arrives (timeout in ms)
pygame.event.post(pygame.event.Event(MY_EVENT, key=value))
MY_EVENT = pygame.event.custom_type()

Functions#

FunctionReturns / does
get(eventtype=None)List of events, removing them from the queue. With eventtype (a type or list of types), only those are returned and removed.
poll()A single event, or an event with type pygame.NOEVENT if the queue is empty.
wait(timeout=0)Waits for the next event. Useful for turn-based tools that don't need a frame rate.
peek(eventtype=None)True if matching events are waiting, without removing them.
clear(eventtype=None)Removes events from the queue.
post(event)Adds an event. Returns whether it was posted.
custom_type()Reserves a new, unique event type number for your own events.
set_blocked(type) / set_allowed(type)Stop or resume putting certain event types in the queue.
pump()Processes internal events without reading the queue. get() already does this.

Common event types and attributes#

TypeAttributes
QUITnone: the window's close button was pressed
KEYDOWN, KEYUPkey, mod, unicode (KEYDOWN), scancode
TEXTINPUTtext: characters typed, with layout and input methods applied
MOUSEBUTTONDOWN, MOUSEBUTTONUPpos, button (1 left, 2 middle, 3 right)
MOUSEMOTIONpos, rel, buttons
MOUSEWHEELx, y (positive y scrolls up)
VIDEORESIZEsize, w, h (resizable windows)
WINDOWFOCUSLOST, WINDOWFOCUSGAINEDwindow focus changes; good moments to auto-pause
JOYBUTTONDOWN, JOYAXISMOTION, …gamepad input; see joystick input

Practical example#

event_example.pyDownload
"""pygame.event: reading the queue, custom events, timers and blocking unwanted events."""
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 24)

SPAWN = pygame.event.custom_type()              # a new, unique event type
pygame.time.set_timer(SPAWN, 1000)              # post SPAWN every 1000 ms
pygame.event.set_blocked(pygame.MOUSEMOTION)    # we don't need motion events here

log = []
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            log.append(f"KEYDOWN {pygame.key.name(event.key)} mod={event.mod}")
            if event.key == pygame.K_b:
                pygame.event.post(pygame.event.Event(SPAWN, source="keyboard"))  # post our own event
        elif event.type == pygame.MOUSEBUTTONDOWN:
            log.append(f"MOUSEBUTTONDOWN button={event.button} pos={event.pos}")
        elif event.type == SPAWN:
            log.append(f"SPAWN from {getattr(event, 'source', 'timer')}")
        elif event.type == pygame.WINDOWFOCUSLOST:
            log.append("Window lost focus")

    screen.fill((20, 26, 46))
    screen.blit(font.render("Press keys, click, press B to post an event", True, (244, 197, 49)), (16, 12))
    for i, line in enumerate(log[-12:]):
        screen.blit(font.render(line, True, (230, 236, 247)), (16, 44 + i * 24))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

This shows a custom event type fired by a timer, a custom event posted with an extra attribute, and motion events blocked because the program doesn't need them.

Common errors#

  • The window freezes or says "Not Responding": the queue isn't read every frame. Call pygame.event.get() (or pump()) every loop.
  • Calling get() twice per frame: the second call returns nothing, because the first emptied the queue. Read once and handle everything in that loop.
  • AttributeError: 'Event' object has no attribute 'key': check event.type before reading type-specific attributes.
  • Using USEREVENT + 1 in several modules can clash. custom_type() hands out unique numbers.

Official documentation#

↑ ↓ to moveEnter to openEsc to close