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!