Master Pyglet: Build Games, Audio, and Video with Python
This tutorial walks you through installing pyglet, creating windows, adding text and images, handling keyboard and mouse events, processing input, and playing audio and video, providing a comprehensive guide to building lightweight Python games and multimedia applications.
Introduction
Unlike pygame, pyglet is simpler and more lightweight, similar to the difference between Django and Flask, making it an attractive choice for quick game development.
1. Installation
pip install pyglet2. Basic Usage
# import module
import pygletYou can list installed packages, inspect modules, and view pyglet's attributes:
pip list import sys
print(sys.modules.keys()) print(dir(pyglet))Key window parameters include width, height, caption, resizable, style, fullscreen, visible, vsync, file_drops, display, screen, config, context, and mode.
width: width
height: height
caption: title
resizable: whether resizable
style: style
fullscreen: fullscreen
visible: visible
vsync: vsync
file_drops: file drops
display: display device
screen: screen
config: config
context: context
mode: modeCreating a simple window:
pyglet.window.Window(600, 600) # create a 600×600 window
pyglet.app.run() # start the app1. Adding Text
Use pyglet.text.Label to display text with various styling options.
label = pyglet.text.Label('Hello',
font_size=40,
x=win.width//2, y=win.height//2,
anchor_x='center', anchor_y='center') @win.event
def on_draw():
win.clear()
label.draw() pyglet.app.run()2. Adding Images
image = pyglet.image.load('2.jpg')
@win.event
def on_draw():
win.clear()
image.blit(0, 0)Alternatively, load via resources: image = pyglet.resource.image('2.jpg') Set image search path:
pyglet.resource.path = ['./images']
pyglet.resource.reindex()
image = pyglet.resource.image('1.jpg')3. Keyboard Events
@win.event
def on_key_press(symbol, modifiers):
if symbol == key.W:
print('forward')
elif symbol == key.S:
print('backward')
elif symbol == key.A:
print('left')
elif symbol == key.D:
print('right')
if modifiers & key.MOD_CTRL:
print('over')4. Mouse Events
@win.event
def on_mouse_motion(x, y, dx, dy):
print('move')
@win.event
def on_mouse_press(x, y, button, modifiers):
print('mouse down')
@win.event
def on_mouse_release(x, y, button, modifiers):
print('mouse up')
@win.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
print('drag')
@win.event
def on_mouse_enter(x, y):
print('enter')
@win.event
def on_mouse_leave(x, y):
print('leave')
@win.event
def on_mouse_scroll(x, y, scroll_x, scroll_y):
print('scroll')5. Input Text Event
@win.event
def on_text(text):
if text == 'i love you':
print('i love you too')4. Window Events
@win.event
def on_resize(width, height):
# handle resize
passEncapsulate in a subclass:
class MyWindow(pyglet.window.Window):
def on_resize(self, width, height):
self.width = 200
self.height = 100
def on_text(self, text):
aa = input('shuru:')
if aa == 'I love you':
print('i love you too')
def on_key_press(self, symbol, modifiers):
if symbol == key.W:
print('forward')
self.width += 100
# other keys...5. Music Playback
# Load and play a wav file
sound = pyglet.media.load('11.wav', streaming=False)
sound.play()
# Using a Player for queueing
player = pyglet.media.Player()
player.queue(sound)
player.play()
# Add multiple tracks
sound1 = pyglet.media.load('2.wav', streaming=False)
player.queue(sound1)
player.play()
# Loop playback with a generator
def loop():
while True:
yield sound
yield sound1
player.queue(loop())
player.play()6. Video Playback
# Load video and display in a window
video = pyglet.media.load('12.mp4')
player = pyglet.media.Player()
player.queue(video)
player.play()
@win.event
def on_draw():
win.clear()
player.get_texture().blit(30, 60)Both pyglet.media.load and pyglet.resource.media can be used for video.
Conclusion
pyglet provides a versatile, lightweight framework for creating games and handling multimedia such as audio and video, offering many useful examples beyond the basics presented here.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
