pyglet is a cross-platform Python library for developing games, multimedia applications, and graphical user interfaces (GUIs). It provides support for creating windows, rendering graphics with OpenGL, handling keyboard and mouse events, displaying images and text, and playing audio and video, making it suitable for building interactive desktop applications.
- Cross-platform support for Windows, macOS, and Linux.
- Create multiple windows and fullscreen applications.
- OpenGL-based graphics rendering.
Prerequisites
Before using pyglet, ensure that:
- Python is installed.
- pip is available.
- Your system supports OpenGL.
Installation
Install pyglet using following command:
pip install pyglet
Basic Structure of a pyglet Application
A pyglet application consists of a few core components that work together to create and display a graphical application.
- Import pyglet: Imports the library and provides access to its modules and classes.
- Create a Window: A Window object represents the main application window where graphics are displayed.
- Create Drawable Objects: Add objects such as labels, images, or sprites that will be rendered inside the window.
- Register Event Handlers: Define event handler functions (such as on_draw()) to respond to events like drawing, keyboard input, and mouse actions.
- Start the Event Loop: Call pyglet.app.run() to start the application's event loop and keep the window responsive.
import pyglet
# Create the application window
window = pyglet.window.Window(
width=600,
height=400,
caption="My First pyglet Application"
)
# Create a label
label = pyglet.text.Label(
"Hello, World!",
x=window.width // 2,
y=window.height // 2,
anchor_x="center",
anchor_y="center"
)
# Draw the window contents
@window.event
def on_draw():
window.clear()
label.draw()
# Start the application
pyglet.app.run()
Output

Explanation:
- pyglet.window.Window() creates the main application window.
- pyglet.text.Label() creates a text label that is displayed inside the window.
- @window.event registers the on_draw() event handler, which is called whenever the window needs to be redrawn.
- window.clear() clears the window before drawing new content.
- label.draw() renders the label on the window.
- pyglet.app.run() starts the event loop and keeps the application running until the window is closed.
Note: Every pyglet application starts by creating a Window object and ends by calling pyglet.app.run(). The event loop continuously processes events and redraws the window whenever required.
Common pyglet Components
| Component | Purpose |
|---|---|
| Window | Main application window |
| Label | Display text |
| Sprite | Draw images |
| Clock | Schedule functions |
| Media | Play audio/video |