pyglet.event

Event dispatch framework.

All objects that produce events in pyglet implement EventDispatcher, providing a consistent interface for registering and manipulating event handlers. A commonly used event dispatcher is pyglet.window.Window.

Event types

For each event dispatcher there is a set of events that it dispatches; these correspond with the type of event handlers you can attach. Event types are identified by their name, for example, ‘’on_resize’’. If you are creating a new class which implements EventDispatcher, you must call EventDispatcher.register_event_type for each event type.

Attaching event handlers

An event handler is simply a function or method. You can attach an event handler by setting the appropriate function on the instance:

def on_resize(width, height):
    # ...
dispatcher.on_resize = on_resize

There is also a convenience decorator that reduces typing:

@dispatcher.event
def on_resize(width, height):
    # ...

You may prefer to subclass and override the event handlers instead:

class MyDispatcher(DispatcherClass):
    def on_resize(self, width, height):
        # ...

Event handler stack

When attaching an event handler to a dispatcher using the above methods, it replaces any existing handler (causing the original handler to no longer be called). Each dispatcher maintains a stack of event handlers, allowing you to insert an event handler “above” the existing one rather than replacing it.

There are two main use cases for “pushing” event handlers:

  • Temporarily intercepting the events coming from the dispatcher by pushing a custom set of handlers onto the dispatcher, then later “popping” them all off at once.

  • Creating “chains” of event handlers, where the event propagates from the top-most (most recently added) handler to the bottom, until a handler takes care of it.

Use EventDispatcher.push_handlers to create a new level in the stack and attach handlers to it. You can push several handlers at once:

dispatcher.push_handlers(on_resize, on_key_press)

If your function handlers have different names to the events they handle, use keyword arguments:

dispatcher.push_handlers(on_resize=my_resize, on_key_press=my_key_press)

After an event handler has processed an event, it is passed on to the next-lowest event handler, unless the handler returns EVENT_HANDLED, which prevents further propagation.

To remove all handlers on the top stack level, use EventDispatcher.pop_handlers.

Note that any handlers pushed onto the stack have precedence over the handlers set directly on the instance (for example, using the methods described in the previous section), regardless of when they were set. For example, handler foo is called before handler bar in the following example:

dispatcher.push_handlers(on_resize=foo)
dispatcher.on_resize = bar

Dispatching events

pyglet uses a single-threaded model for all application code. Event handlers are only ever invoked as a result of calling EventDispatcher.dispatch_events`.

It is up to the specific event dispatcher to queue relevant events until they can be dispatched, at which point the handlers are called in the order the events were originally generated.

This implies that your application runs with a main loop that continuously updates the application state and checks for new events:

while True:
    dispatcher.dispatch_events()
    # ... additional per-frame processing

Not all event dispatchers require the call to dispatch_events; check with the particular class documentation.

Note

In order to prevent issues with garbage collection, the EventDispatcher class only holds weak references to pushed event handlers. That means the following example will not work, because the pushed object will fall out of scope and be collected:

dispatcher.push_handlers(MyHandlerClass())

Instead, you must make sure to keep a reference to the object before pushing it. For example:

my_handler_instance = MyHandlerClass()
dispatcher.push_handlers(my_handler_instance)
exception EventException

An exception raised when an event handler could not be attached.

class EventDispatcher

Generic event dispatcher interface.

See the module docstring for usage.

dispatch_event(event_type, *args)

Dispatch an event to the attached event handlers.

The event is propagated to all registered event handlers in the stack, starting and the top and going down. If any registered event handler returns EVENT_HANDLED, no further handlers down the stack will receive this event.

This method has several possible return values. If any event hander has returned EVENT_HANDLED, then this method will also return EVENT_HANDLED. If not, this method will return EVENT_UNHANDLED. If there were no events registered to receive this event, False is returned.

Parameters:
event_typestr

The name of the event to dispatch.

argssequence

Optional arguments to pass to the event handlers.

Return type:

bool or None

Returns:

EVENT_HANDLED if any event handler returned EVENT_HANDLED; EVENT_UNHANDLED if one or more event handlers were invoked without any of them returning EVENT_HANDLED; False if no event handlers were registered.

event(*args)

Function decorator for an event handler.

Usage:

win = window.Window()

@win.event
def on_resize(self, width, height):
    # ...

or:

@win.event('on_resize')
def foo(self, width, height):
    # ...
pop_handlers()

Pop the top level of event handlers off the stack.

push_handlers(*args, **kwargs)

Push a level onto the top of the handler stack, then attach zero or more event handlers.

If keyword arguments are given, they name the event type to attach. Otherwise, a callable’s __name__ attribute will be used. Any other object may also be specified, in which case it will be searched for callables with event names.

classmethod register_event_type(name)

Register an event type with the dispatcher.

Registering event types allows the dispatcher to validate event handler names as they are attached, and to search attached objects for suitable handlers.

Parameters:
namestr

Name of the event to register.

remove_handler(name, handler)

Remove a single event handler.

The given event handler is removed from the first handler stack frame it appears in. The handler must be the exact same callable as passed to set_handler, set_handlers or push_handlers(); and the name must match the event type it is bound to.

No error is raised if the event handler is not set.

Parameters:
namestr

Name of the event type to remove.

handlercallable

Event handler to remove.

remove_handlers(*args, **kwargs)

Remove event handlers from the event stack.

See push_handlers() for the accepted argument types. All handlers are removed from the first stack frame that contains any of the given handlers. No error is raised if any handler does not appear in that frame, or if no stack frame contains any of the given handlers.

If the stack frame is empty after removing the handlers, it is removed from the stack. Note that this interferes with the expected symmetry of push_handlers() and pop_handlers().

set_handler(name, handler)

Attach a single event handler.

Parameters:
namestr

Name of the event type to attach to.

handlercallable

Event handler to attach.

set_handlers(*args, **kwargs)

Attach one or more event handlers to the top level of the handler stack.

See push_handlers() for the accepted argument types.