Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Writing the simple pyglet application

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

It might not be easy to get started with a new library or framework, especially when there is a lot of reference material to read. So in here, we tried putting all the most basic applications that you need to understand and know the implementation if you want to get started with pyglet. Python's pyglet module is a cross-platform windowing and multimedia library for creating games and other visually rich applications. In pyglet, windowing, user interface event management, joysticks, OpenGL graphics, loading photos, movies, sound, and music playback are all supported. 

If you want to know what is pyglet and why it is used, check out this blog.

Source

Hello, World in pyglet

We'll start with the standard "Hello, World" introduction. This program will open a text-filled window and wait for it to be closed.

We’ll start by importing the pyglet package:

import pyglet

 

Make a pyglet.window.window. It calls the default constructor for the window. The window will be visible as soon as it is created, and all of its parameters will have suitable default values:

window = pyglet.window.Window()

 

We'll make a Label to display the text. The font, position, and anchoring of the label are set using 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 numerous 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 cleared to the default backdrop color (black), and the label is drawn within the on_draw() handler.

Finally, call:

pyglet.app.run()

 

This will start the pyglet's default event loop, which will allow it to respond to mouse and keyboard inputs. The run() method will now only return when all program windows have been closed, and your event handlers will be called as required.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Image Viewer

We had discussed how to write a simple application in pyglet. Now we'll load an image from the application's directory and display it in the window. It is crucial because the majority of games and programs will require graphics to load and display on the screen. Now let's see how to do it,  

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 use the image() function in pyglet.resource, it automatically locates the file relative to the source file (rather than the working directory). pyglet.image.load is used to load an image that is not included with the application 

The image is drawn using the blit() technique. The arguments (0, 0) instruct the pyglet to draw the picture in the window at pixel coordinates 0, 0. (the lower-left corner).

Handling mouse and Keyboard events

The on_draw() event has been the only one used so far. It's also essential to write and attach event handlers for keyboard and mouse events in order 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()

 

The virtual key symbol pressed, and a bitwise combination of any modifiers present are the two parameters of keyboard events (for example, the CTRL and SHIFT keys).

pyglet.window.key defines the key symbols:

from pyglet.window import key


@window.event
def on_key_press(symbol, modifiers):
    if symbol == key.A:
        print('The "A" key was pressed.')
    elif symbol == key.LEFT:
        print('The left arrow key was pressed.')
    elif symbol == key.ENTER:
        print('The enter key was pressed.')

 

Similarly, mouse events are handled:

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 parameters indicate where the mouse was when the button was pressed in relation to the window's lower-left corner.

 

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

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

 

All events received on the window will be printed to the console as a result of this.

Playing Sounds and Music

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

import pyglet

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

pyglet.app.run()

 

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

When playing, audio is streamed by default. This is especially useful for lengthier music tracks. Short noises, such as a game's gunshot, should instead be fully decoded in memory. This allows 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 scenario, set streaming=False:

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

FAQs

What is pyglet?

pyglet is a cross-platform windowing and multimedia library for Python.

What are the events of the keyboard, and how to trigger them?

The virtual key symbol that was pressed and a bitwise combination of any modifiers present are two events of the keyboard (to trigger it, press the CTRL and SHIFT keys).

When is any media supposed to be imported, and where it will get imported from?

The media (image or sound) files are present in the application’s directory, not in the working directory.

Conclusion

In this article, we have extensively discussed the applications and their implementations that you should know while starting pyglet. We had written hello, world program, inserted images, handled mouse and keyboard events, and how to play sounds and music. You should check this out to know more about pyglet applications. You should also check out this; it will help you with the concept of pygame, a python project. If you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available, interview puzzles. Also, look at the interview experiences and interview bundle for placement preparations. Please look at this YouTube tutorial to explore the preparation strategy for SDE placements.

Happy learning!

Topics covered
1.
Introduction
2.
Hello, World in pyglet
3.
Image Viewer
4.
Handling mouse and Keyboard events
5.
Playing Sounds and Music
6.
FAQs
6.1.
What is pyglet?
6.2.
What are the events of the keyboard, and how to trigger them?
6.3.
When is any media supposed to be imported, and where it will get imported from?
7.
Conclusion