-
pygame.event - pygame module for interacting with events and queues
— internally process pygame event handlers — get events from the queue — get a single event from the queue — wait for a single event from the queue — test if event types are waiting on the queue — remove all events from the queue — get the string name from an event id — control which events are blocked on the queue — control which events are allowed on the queue — test if a type of event is blocked from the queue — control the sharing of input devices with other applications — test if the program is sharing input devices — place a new event on the queue — make custom user event type — pygame object for representing events Event queue
Pygame handles all its event messaging through an event queue. The functions in this module help you manage that event queue. The input queue is heavily dependent on the video system (
pygame.displayPygame module to control the display window and screen. orpygame.WindowPygame object that represents a window.). If a window has not been created, the event queue may not work properly.The event queue has an upper limit on the number of events it can hold. When the queue becomes full new events are quietly dropped. To prevent lost events, especially input events which signal a quit command, your program must handle events every frame (with
pygame.event.get()get events from the queue,pygame.event.pump()internally process pygame event handlers,pygame.event.wait()wait for a single event from the queue,pygame.event.peek()test if event types are waiting on the queue orpygame.event.clear()remove all events from the queue).Note
Not handling events may cause the system to decide the program is frozen (not responding).
Events of input devices
To get the state of various input devices, you can forego the event queue and access the input devices directly with their appropriate modules:
pygame.mousePygame module to work with the mouse.,pygame.keyPygame module to work with the keyboard., andpygame.joystickPygame module for interacting with joysticks, gamepads, and trackballs.. However, the event queue still needs to be running internally to enable this; programs still need to use functions likepygame.event.get()get events from the queue orpygame.event.pump()internally process pygame event handlers periodically. Note: Joysticks will not send any events until the device has been initialized.Event objects
The event queue contains
pygame.event.Eventpygame object for representing events event objects. There are a variety of ways to access the queued events, from simply checking for the existence of events, to popping them off of the event queue.All
pygame.event.Eventpygame object for representing events instances contain an event type identifier and attributes specific to that event type. The event type identifier is accessible as thepygame.event.Event.typeevent type identifier. property. An event type's specific attributes can be accessed directly as an attribute on the event object.Users can create their own new events (or emulate system events) by instantiating
pygame.event.Event()pygame object for representing events themselves, usually paired withpygame.event.post()place a new event on the queue.Events support equality and inequality comparisons. Two events are equal if they are the same type and have identical attribute values.
Custom events and debugging
The event type identifier is in between the values of
NOEVENTandNUMEVENTS. User defined events should have a value in the inclusive range ofUSEREVENTtoNUMEVENTS - 1. User defined events should reserve a custom event number withpygame.event.custom_type()make custom user event type.While debugging and experimenting, you can print an event object for a quick display of its type and members.
Event types and attributes
Events that come from the system will have a guaranteed set of member attributes based on the type. The following are lists of event types with their specific attributes and notes.
You can also find a list of constants for keyboard keys here.
Event type Attributes/Notes QUIT USEREVENT (Starting type of the user defined event types) KEYDOWN key, mod, unicode, scancode, window(1) KEYUP key, mod, unicode, scancode, window(1) MOUSEMOTION pos, rel, buttons, touch(2), window(1) MOUSEBUTTONUP pos, button, touch(2), clicks(3), window(1) MOUSEBUTTONDOWN pos, button, touch(2), clicks(3), window(1) MOUSEWHEEL which, flipped, x, y, touch(2), precise_x, precise_y, window(1) JOYAXISMOTION instance_id, axis, value (deprecated: joy) JOYBALLMOTION instance_id, ball, rel (deprecated: joy) JOYHATMOTION instance_id, hat, value (deprecated: joy) JOYBUTTONUP instance_id, button (deprecated: joy) JOYBUTTONDOWN instance_id, button (deprecated: joy) CONTROLLERDEVICEADDED device_index JOYDEVICEADDED device_index CONTROLLERDEVICEREMOVED instance_id JOYDEVICEREMOVED instance_id CONTROLLERDEVICEREMAPPED instance_id (Use the window event API instead of legacy events) ACTIVEEVENT gain, state (Legacy event) VIDEORESIZE size, w, h (Legacy event) VIDEOEXPOSE (Legacy event) AUDIODEVICEADDED which, iscapture AUDIODEVICEREMOVED which, iscapture FINGERMOTION touch_id, finger_id, x, y, dx, dy, window(1) FINGERDOWN touch_id, finger_id, x, y, dx, dy, window(1) FINGERUP touch_id, finger_id, x, y, dx, dy, window(1) MULTIGESTURE touch_id, x, y, pinched, rotated, num_fingers TEXTEDITING(4) text, start(4), length(4), window(1) TEXTINPUT(4) text, window(1) DROPFILE window(1), file (Path of the file dropped on the window) DROPBEGIN window(1) DROPCOMPLETE window(1) DROPTEXT window(1) MIDIIN (Reserved for pygame.midi use) MIDIOUT (Reserved for pygame.midi use) KEYMAPCHANGED (Keymap change due to language/keyboard layout change) CLIPBOARDUPDATE (Partially experimental) LOCALECHANGED RENDER_TARGETS_RESET RENDER_DEVICE_RESET
(
1): if apygame.WindowPygame object that represents a window. instance exists for the window that the event occurred in, thewindowattribute of these events will be that instance, otherwise it will beNone.(
2): Thetouchattribute ofMOUSEevents indicates whether or not the events were generated by a touch input device, and not a real mouse. You might want to ignore such events, if your application already handlesFINGERMOTION,FINGERDOWNandFINGERUPevents.(
3): Theclicksattribute of theMOUSEBUTTONDOWNandMOUSEBUTTONUPevents indicate the number of clicks occurring in rapid succession, e.g.1for single-click,2for double-click, etc. Note that double, triple, or more clicks will still fire mouse events for each individual click, with a progressively increasingclicksattribute.(
4): Thestartattribute of theTEXTEDITINGevent is the cursor position, in UTF-8 characters, where the new typing will be inserted into the editing text, while thelengthattribute is the number of UTF-8 characters that will be replaced by the new typing.These
TEXT*events are useful to implement inputs/languages that require composition, provided by the system's IME (Input Method Editor). TheTEXTINPUTevent is only fired when the text is confirmed.Here is a list of the new window events.
All window events have a
windowattribute corresponding to thepygame.WindowPygame object that represents a window. that generated them.Event type Short description and additional attributes WINDOWSHOWN Window became shown WINDOWHIDDEN Window became hidden WINDOWEXPOSED Window got updated by some external event WINDOWMOVED Window got moved (x, y attributes) WINDOWSIZECHANGED Window size has changed (x, y attributes) WINDOWRESIZED Window got resized by the user/window manager (x, y attributes) WINDOWMINIMIZED Window was minimized WINDOWMAXIMIZED Window was maximized WINDOWRESTORED Window was restored WINDOWENTER Mouse entered the window WINDOWLEAVE Mouse left the window WINDOWFOCUSGAINED Window gained focus WINDOWFOCUSLOST Window lost focus WINDOWCLOSE Window was closed WINDOWTAKEFOCUS Window was offered focus WINDOWHITTEST Window has a special hit test WINDOWICCPROFCHANGED Window ICC profile changed (SDL backend >= 2.0.18) WINDOWDISPLAYCHANGED Window moved on a new display (display_index attribute. SDL backend >= 2.0.18)
On Android, the following events can be generated:
Event type Short description APP_TERMINATING OS is terminating the application APP_LOWMEMORY OS is low on memory (try to free memory) APP_WILLENTERBACKGROUND Application is entering background APP_DIDENTERBACKGROUND Application entered background APP_WILLENTERFOREGROUND Application is entering foreground APP_DIDENTERFOREGROUND Application entered foreground
Changed in pygame 2.0.0: The
joyattribute was deprecated,instance_idwas added.New in pygame 2.0.1: Window events and the
unicodeattribute forKEYUPevents.New in pygame 2.0.2: The
touchattribute was added to all theMOUSEevents.New in pygame-ce 2.1.3: Android events,
precise_xandprecise_ytoMOUSEWHEELevents,KEYMAPCHANGED,CLIPBOARDUPDATE,LOCALECHANGED,WINDOWICCPROFCHANGED,WINDOWDISPLAYCHANGED,RENDER_TARGETS_RESET, andRENDER_DEVICE_RESET.New in pygame-ce 2.5.7: The
clicksattribute was added toMOUSEBUTTONDOWNandMOUSEBUTTONUPevents.- pygame.event.pump()¶
- internally process pygame event handlerspump() -> None
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system. If you are not using other event functions in your game, you should call
pygame.event.pump()to allow pygame to handle internal actions.This function is not necessary if your program is consistently processing events on the queue through the other
pygame.eventpygame module for interacting with events and queues functions.There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.
Caution
This function should only be called in the thread that initialized
pygame.displayPygame module to control the display window and screen..
- pygame.event.get()¶
- get events from the queueget(eventtype=None) -> Eventlistget(eventtype=None, pump=True) -> Eventlistget(eventtype=None, pump=True, exclude=None) -> Eventlist
This will get all the messages and remove them from the queue. If a type or sequence of types is given only those messages will be removed from the queue and returned.
If a type or sequence of types is passed in the
excludeargument instead, then all only other messages will be removed from the queue. If anexcludeparameter is passed, theeventtypeparameter must be None.If you are only taking specific events from the queue, be aware that the queue could eventually fill up with the events you are not interested.
If
pumpisTrue(the default), thenpygame.event.pump()internally process pygame event handlers will be called.Changed in pygame 1.9.5: Added
pumpargumentChanged in pygame 2.0.2: Added
excludeargument
- pygame.event.poll()¶
- get a single event from the queuepoll() -> Event instance
Returns a single event from the queue. If the event queue is empty an event of type
pygame.NOEVENTwill be returned immediately. The returned event is removed from the queue.Caution
This function should only be called in the thread that initialized
pygame.displayPygame module to control the display window and screen..
- pygame.event.wait()¶
- wait for a single event from the queuewait() -> Event instancewait(timeout) -> Event instance
Returns a single event from the queue. If the queue is empty this function will wait until one is created. From pygame 2.0.0, if a
timeoutargument is given, the function will return an event of typepygame.NOEVENTif no events enter the queue intimeoutmilliseconds. The event is removed from the queue once it has been returned. While the program is waiting it will sleep in an idle state. This is important for programs that want to share the system with other applications.Changed in pygame 2.0.0.dev13: Added
timeoutargumentCaution
This function should only be called in the thread that initialized
pygame.displayPygame module to control the display window and screen..
- pygame.event.peek()¶
- test if event types are waiting on the queuepeek(eventtype=None) -> boolpeek(eventtype=None, pump=True) -> bool
Returns
Trueif there are any events of the given type waiting on the queue. If a sequence of event types is passed, this will returnTrueif any of those events are on the queue.When
eventtypeis not passed orNone, this function will returnTrueif there's any event on the queue, and returnFalseif the queue is empty.If
pumpisTrue(the default), thenpygame.event.pump()internally process pygame event handlers will be called.Changed in pygame 1.9.5: Added
pumpargumentChanged in pygame-ce 2.5.3: no longer mistakenly returns an event when
eventtypeis None or not passed.
- pygame.event.clear()¶
- remove all events from the queueclear(eventtype=None) -> Noneclear(eventtype=None, pump=True) -> None
Removes all events from the queue. If
eventtypeis given, removes the given event or sequence of events. This has the same effect aspygame.event.get()get events from the queue exceptNoneis returned. It can be slightly more efficient when clearing a full event queue.If
pumpisTrue(the default), thenpygame.event.pump()internally process pygame event handlers will be called.Changed in pygame 1.9.5: Added
pumpargument
- pygame.event.event_name()¶
- get the string name from an event idevent_name(type, /) -> string
Returns a string representing the name (in CapWords style) of the given event type.
"UserEvent" is returned for all values in the user event id range. "Unknown" is returned when the event type does not exist.
- pygame.event.set_blocked()¶
- control which events are blocked on the queueset_blocked(type, /) -> Noneset_blocked(typelist, /) -> Noneset_blocked(None) -> None
The given event types are not allowed to appear on the event queue. By default all events can be placed on the queue. It is safe to disable an event type multiple times.
If
Noneis passed as the argument, ALL of the event types are blocked from being placed on the queue.
- pygame.event.set_allowed()¶
- control which events are allowed on the queueset_allowed(type, /) -> Noneset_allowed(typelist, /) -> Noneset_allowed(None) -> None
The given event types are allowed to appear on the event queue. By default, all event types can be placed on the queue. It is safe to enable an event type multiple times.
If
Noneis passed as the argument, ALL of the event types are allowed to be placed on the queue.
- pygame.event.get_blocked()¶
- test if a type of event is blocked from the queueget_blocked(type, /) -> boolget_blocked(typelist, /) -> bool
Returns
Trueif the given event type is blocked from the queue. If a sequence of event types is passed, this will returnTrueif any of those event types are blocked.
- pygame.event.set_grab()¶
- control the sharing of input devices with other applicationsset_grab(bool, /) -> None
When your program runs in a windowed environment, it will share the mouse and keyboard devices with other applications that have focus. If your program sets the event grab to
True, it will lock all input into your program.It is best to not always grab the input, since it prevents the user from doing other things on their system.
- pygame.event.get_grab()¶
- test if the program is sharing input devicesget_grab() -> bool
Returns
Truewhen the input events are grabbed for this application.
- pygame.event.post()¶
- place a new event on the queuepost(event, /) -> bool
Places the given event at the end of the event queue.
This is usually used for placing custom events on the event queue. Any type of event can be posted, and the events posted can have any attributes.
When this event is received on the event queue, it will be a shallow copy of the event object posted by this function; the dict attribute of both events will be a reference to the same dict object in memory. Modifications on one dict can affect another, use deepcopy operations on the dict object if you don't want this behaviour.
This returns a boolean on whether the event was posted or not. Blocked events cannot be posted, and this function returns
Falseif you try to post them.Changed in pygame 2.0.1: returns a boolean, previously returned
None
- pygame.event.custom_type()¶
- make custom user event typecustom_type() -> int
Reserves an event slot for use in a custom event
usereventand returns the integer that the event slot is reserved to.If too many events are made a
pygame.errorstandard pygame exception is raised.New in pygame 2.0.0.dev3.
- pygame.event.Event¶
- pygame object for representing eventsEvent(type, dict) -> EventEvent(type, **attributes) -> Event
— event type identifier. — event attribute dictionary A pygame object used for representing an event.
Eventinstances support attribute assignment and deletion.When creating the object, the attributes may come from a dictionary argument with string keys or from keyword arguments.
Changed in pygame-ce 2.1.4: This class is also available through the
pygame.Eventalias.Note
From version 2.1.3
EventTypeis an alias forEvent. Beforehand,Eventwas a function that returnedEventTypeinstances. Use ofEventis preferred overEventTypewherever it is possible, as the latter could be deprecated in a future version.- type¶
- event type identifier.type -> int
Read-only. The event type identifier. For user created event objects, this is the
typeargument passed topygame.event.Event()pygame object for representing events.For example, some predefined event identifiers are
QUITandMOUSEMOTION.
- __dict__¶
- event attribute dictionary__dict__ -> dict
Read-only. The event type specific attributes of an event. The
dictattribute is a synonym for backward compatibility.For example, the attributes of a
KEYDOWNevent would beunicode,key, andmod
New in pygame 1.9.2: Mutable attributes.
Edit on GitHub