Introduction
Pyglet is a library provided by python to develop games, cross-platform windowing, and multimedia. Pyglet supports user interface event handling, windowing, game controllers, graphics, loading images, videos, etc. The pyglet library can be imported and works on various operating systems like Windows, OS X, and Linux.
pyglet.event
The pyglet.event module in the pyglet library dispatches the events in an application. The objects in this submodule implement the EventDispatcher interface for registering and manipulating the event registers. We can dispatch the events using the dispatch_events() method. This method dispatches the events on the application window.
window.dispatch_events()Attaching event handlers
An event handler can be attached by setting the necessary function on the instance. Suppose you want to dispatch an event to resize the window of an application. You can declare the resize method and add the instance to the dispatcher function.
def on_resize(width, height):
# ...
dispatcher.on_resize = on_resizeEvent handler stack
Whenever any new event is dispatched, the current event gets replaced with the new one. All the events are stored in a stack, and the newly dispatched event is always placed on the top of current events, which pops the previous event out of the stack. We can push the event handlers to the stack using the following method.
dispatcher.push_handlers(on_resize, on_key_press)Dispatching events
The pyglet library uses a single-threaded model for the code in any application. So the queue of events and dispatching, calling the events entirely depends on the event dispatcher. The application runs in a loop, which dispatches the events and continuously checks the application state and new events.
import pyglet
import pyglet.window.key
width = 500
height = 500
title = "pyglet blog"
window = pyglet.window.Window(width, height, title)
text = "Pyglet.event submodule"
label = pyglet.text.Label(text,
font_name ='Arial',
font_size = 36,
x =15,
y = 15)
@window.event
def on_draw():
window.clear()
label.draw()
@window.event
def on_key_press(symbol, modifier):
if symbol == pyglet.window.key.esc:
window.close()
window.dispatch_events()
pyglet.app.run()
In the above code, we created a window with a height and width of 500, a label with the Arial font, and a font size of 36 with the position. The method on_draw() clears the window and draws a new label created before it. Then the method on_key_press closes the window if the pressed key is “esc”. The event will be dispatched, and the application will be run to execute the event.




