Setting event handlers

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

Note that you need not even name your function the same as the event.

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

You can even give the event handler another name if necessary:

@window.event('on_resize')
def handle_resize_event(width, height):
    pass

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

In this case you must use the name of the event handler as the method name.