An event handler is simply a function with a formal parameter list corresponding to the event type. For example, the Window.on_resize event has the parameters (width, height), so an event handler for this event could be:
def on_resize(width, height): pass
The Window class subclasses EventDispatcher, which enables it to have event handlers attached to it. The simplest way to attach an event handler is to set the corresponding attribute on the object:
window = pyglet.window.Window() def on_resize(width, height): pass window.on_resize = on_resize
While this technique is straight-forward, it requires you to write the name of the event three times for the one function, which can get tiresome. pyglet provides a shortcut using the event decorator:
window = window.Window() @window.event def on_resize(width, height): pass
This is not entirely equivalent to setting the event handler directly on the object. If the object already had an event handler, using @event will add the handler to the object, rather than replacing it. The next section describes this functionality in detail.
As shown in Subclassing Window, you can also attach event handlers by subclassing the event dispatcher and adding the event handler as a method:
class MyWindow(pyglet.window.Window): def on_resize(self, width, height): pass