Hello, World

We'll begin with the requisite "Hello, World" introduction. This program will open a window with some text in it and wait to be closed. You can find the entire program in the examples/programming_guide/hello_world.py file.

Begin by importing the pyglet package:

import pyglet

Create a Window by calling its default constructor. The window will be visible as soon as it's created, and will have reasonable default values for all its parameters:

window = pyglet.window.Window()

To display the text, we'll create a Label. Keyword arguments are used to set the font, position and anchorage of the label:

label = pyglet.text.Label('Hello, world',
                          font_name='Times New Roman',
                          font_size=36,
                          x=window.width//2, y=window.height//2,
                          anchor_x='center', anchor_y='center')

An on_draw event is dispatched to the window to give it a chance to redraw its contents. pyglet provides several ways to attach event handlers to objects; a simple way is to use a decorator:

@window.event
def on_draw():
    window.clear()
    label.draw()

Within the on_draw handler the window is cleared to the default background color (black), and the label is drawn.

Finally, call:

pyglet.app.run()

To let pyglet respond to application events such as the mouse and keyboard. Your event handlers will now be called as required, and the run method will return only when all application windows have been closed.

Note that earlier versions of pyglet required the application developer to write their own event-handling runloop. This is still possible, but discouraged; see The application event loop for details.