Customising the event loop

The pyglet event loop is encapsulated in the EventLoop class, which provides several hooks that can be overridden for customising its behaviour. This is recommended only for advanced users -- typical applications and games are unlikely to require this functionality.

To use the EventLoop class directly, instantiate it and call run:

pyglet.app.EventLoop().run()

Only one EventLoop can be running at a time; when the run method is called the module variable pyglet.app.event_loop is set to the running instance. Other pyglet modules such as pyglet.window depend on this.

Event loop events

You can listen for several events on the event loop instance. The most useful of these is on_window_close, which is dispatched whenever a window is closed. The default handler for this event exits the event loop if there are no more windows. The following example overrides this behaviour to exit the application whenever any window is closed:

event_loop = pyglet.app.EventLoop()

@event_loop.event
def on_window_close(window):
    event_loop.exit()
    return pyglet.event.EVENT_HANDLED

event_loop.run()

Overriding the default idle policy

The EventLoop.idle method is called every iteration of the event loop. It is responsible for calling scheduled clock functions, redrawing windows, and deciding how idle the application is. You can override this method if you have specific requirements for tuning the performance of your application; especially if it uses many windows.

The default implementation has the following algorithm:

  1. Call clock.tick with poll=True to call any scheduled functions.
  2. Dispatch the on_draw event and call flip on every open window.
  3. Return the value of clock.get_sleep_time.

The return value of the method is the number of seconds until the event loop needs to iterate again (unless there is an earlier user-input event); or None if the loop can wait for input indefinitely.

Note that this default policy causes every window to be redrawn during every user event -- if you have more knowledge about which events have an effect on which windows you can improve on the performance of this method.