Table of contents
1.
Introduction
2.
Pyglet's Characteristics
3.
Developing a Python application
3.1.
Hello, Universe!
3.2.
Viewer of images
3.3.
Sound and music are being played
4.
What's next?
5.
Frequently Asked Questions
5.1.
Pyglet or Pygame: which is better?
5.2.
What is the purpose of Pyglet?
5.3.
What exactly is pyglet GL?
5.4.
What is the purpose of pyglet?
5.5.
Is Pyglet compatible with Mac?
6.
Conclusion
Last Updated: Mar 27, 2024

Application Resources in Pyglet

Author Palak Mishra
0 upvote

Introduction

Python's pyglet library is a cross-platform windowing and multimedia library designed for creating games and other visually rich applications. It has windowing, user interface event handling, game controllers and joysticks, OpenGL graphics, image, video loading, and sound and music playback capabilities. Pythonglet is compatible with Windows, Mac OS X, and Linux.

Pyglet's Characteristics

  • There are no prerequisites for installation
  • on or external dependencies. Pyglet requires no other software than Python to run most applications and games, making distribution and installation accessible.
  • Use multi-monitor desktops and multiple windows. pyglet supports as many windows as you need and is fully aware of multi-monitor setups for fullscreen games and apps.
  • You can load almost any image, sound, music, or video format. pyglet comes with built-in support for standard audio and image formats and can use FFmpeg to load virtually any compressed audio or video file.
  • Pyglet is released under the BSD open-source license, allowing you to use it for commercial and open-source projects.

Developing a Python application

It can be challenging to get started with a new library or framework, especially when there is a lot of reference material to read. This chapter provides a brief overview of pyglet without going into depth.

Hello, Universe!

We'll start with the standard "Hello, World" greeting. This program will open a text-filled window and wait for it to be closed. The entire program can be found in the examples/programming guide/hello world.py file.

Install the  pyglet package first:

import pyglet

 

Make a pyglet.window.Window. Window's default constructor is called. The window will be visible as soon as it is created, and all of its parameters will have reasonable default values:

window = pyglet.window.Window()

 

We'll use a Label to display the text.The label's font, size, and placement  are controlled by keyword arguments:

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')

 

The window receives an on draw() event, which allows it to redraw its contents. There are several ways to attach event handlers to objects in pyglet; one of the simplest is to use a decorator:

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

 

The window is reset to its default background color (black), and the label is drawn within the on draw() handler.

Last but not least, dial:

pyglet.app.run()

 

This will put the pyglet into its default event loop, allowing it to respond to mouse and keyboard events. Your event handlers will be called as needed now, and the run() method will only return once all application windows have been closed.

You might be used to writing your event loop if you're coming from another library. This can also be done with pyglet, but it's not recommended. 

Viewer of images

Most games and applications will require images to load and display on the screen. We'll load an image from the application's directory and display it in the window in this example:

 

import pyglet

window = pyglet.window.Window()
image = pyglet.resource.image('kitten.jpg')

@window.event
def on_draw():
    window.clear()
    image.blit(0, 0)

pyglet.app.run()

 

To load the image, we used the image()function in pyglet.resource, which automatically locates the file relative to the source file (rather than the working directory). You'd use pyglet.image.load to load an image that wasn't included with the app (for example, one specified on the command line) ().

The image is drawn with the  blit() method. The arguments (0, 0) instruct Python to remove the image in the window at pixel coordinates 0, 0. (the lower-left corner).

Mouse and keyboard events are handled.

The on draw() event has been the only one used. It's also necessary to write and attach event handlers for keyboard and mouse events to react to them:

 

import pyglet

window = pyglet.window.Window()

@window.event
def on_key_press(symbol, modifiers):
    print('A key was pressed')

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

pyglet.app.run()

 

Similar rules apply to mouse events:

from pyglet.window import mouse

@window.event
def on_mouse_press(x, y, button, modifiers):
    if button == mouse.LEFT:
print('The left mouse button was pressed.')

 

The x and y coordinates indicate where the mouse was concerning the window's lower-left corner when the button was pressed.

On a window, you can handle over 20 different event types. Add the following lines to your program to quickly find the event names and parameters you require:

vent_logger = pyglet.window.event.WindowEventLogger()
window.push_handlers(event_logger)

All events received on the window will be printed to the console with this command.

Sound and music are being played

Pyglet makes it simple to play and combines multiple sounds. The example below plays an MP3 file.

import pyglet


music = pyglet.resource.media('music.mp3')
music.play()


pyglet.app.run()

Like the image loading example, media() looks for the sound file in the application's directory (not the working directory). If you know the path to the filesystem (relative or absolute), use: pyglet.media.load().

When playing, audio is streamed by default. This is especially useful for longer music tracks. Short sounds, such as a game's gunshot, should instead be fully decoded in memory before being used. This enables them to play more quickly while incurring fewer CPU performance penalties. It also allows you to play the same sound without reloading it. In this case, set streaming=False.

Like the image loading example, media() looks for the sound file in the application's directory (not the working directory). Use pyglet.media.load if you know the actual filesystem path (relative or absolute) ().

Audio is streamed by default when playing. This is particularly useful for longer music tracks. Short sounds, such as a game's gunshot, should be fully decoded in memory before being used. This allows them to play more quickly and with less CPU usage. It also allows you to play the same sound repeatedly without reloading it. In this case, specify 

streaming=False:


sound = pyglet.resource.media('shot.wav', streaming=False)
sound.play()


The examples/media player.py example shows how to use pyglet to playback streaming audio and video. In the example examples/noisy/noisy.py , many short audio samples are played simultaneously, as in a game.

What's next?

The preceding examples demonstrated how to show something on the screen and perform a few simple tasks. Don't worry if these examples leave you with many unanswered questions. Many of pyglet's features are covered in greater technical detail in the rest of this programming guide. If you're a seasoned programmer, you'll be able to jump right into the sections that interest you.

Reading everything at once can be intimidating for new users. If you're feeling overwhelmed, start at the beginning of each chapter and work your way through an example project.

Frequently Asked Questions

Pyglet or Pygame: which is better?

Pyglet is faster and has better performance than pygame. Speed is always a concern when developing a game.

What is the purpose of Pyglet?

Pyglet is a Python library that provides an object-oriented programming interface for creating games and other multimedia applications. Pyglet is a BSD-licensed program that runs on Microsoft Windows, Mac OS X, and Linux.

What exactly is pyglet GL?

OpenGL and GLU are both supported by pyglet. Pyglet's higher-level APIs all use this interface. APIs, allow the graphics card to render data more efficiently than the operating system.

What is the purpose of pyglet?

Pyglet is a Python library that provides an object-oriented application programming interface for developing games and other multimedia applications. Pyglet is a BSD-licensed program that runs on Microsoft Windows, macOS, and Linux.

Is Pyglet compatible with Mac?

Pyglet is a powerful yet straightforward Python library for creating games and other visually appealing software for Windows, Mac OS X, and Linux. Windowing, user interface event handling, joysticks, OpenGL graphics, image loading, and video playback are just a few covered topics. And sound and music playback are all supported. 

Conclusion

We hope you have found this blog's info according to what you needed as the topic of visually rich Pyglet applications is extensively discussed in this article. And for additional information about Pyglet resources, check out our Pyglet articles. Still, the learning never stops. Look at more related articles: PygletPyGameSQLBasic Of Python, and to further knowledge, see Operating SystemUnix File SystemFile System Routing, and File Input/Output.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass