Python Multimedia — Save 50%
Learn how to develop Multimedia applications using Python with this practical step-by-step guide
Animation is a sequence of frames displayed quickly one after the other. This creates an optical illusion where the objects, for instance, appear to be moving around. This article by Ninad Sathaye, author of Python Multimedia Beginner's Guide, will introduce you to the fundamentals of developing animations using Python and Pyglet multimedia application development frameworks. Pyglet is designed to do 3D operations, but we will use it for developing very simple 2D animations in this article. Specifically, we will:
- Learn the basics of Pyglet framework. This will be used to develop code to create or play animations.
- Learn how to play an existing animation file and create animations using a sequence of images.
(For more resources on Python, see here.)
So let's get on with it.
We will cover the prerequisites for the installation of Pyglet in this section.
Pyglet provides an API for multimedia application development using Python. It is an OpenGL-based library, which works on multiple platforms. It is primarily used for developing gaming applications and other graphically-rich applications. Pyglet can be downloaded from http://www.pyglet.org/download.html. Install Pyglet version 1.1.4 or later. The Pyglet installation is pretty straightforward.
For Windows users, the Pyglet installation is straightforward—use the binary distribution Pyglet 1.1.4.msi or later.
You should have Python 2.6 installed. For Python 2.4, there are some more dependencies. We won't discuss them in this article, because we are using Python 2.6 to build multimedia applications.
If you install Pyglet from the source, see the instructions under the next sub-section, Other platforms.
The Pyglet website provides a binary distribution file for Mac OS X. Download and install pyglet-1.1.4.dmg or later.
On Linux, install Pyglet 1.1.4 or later if it is available in the package repository of your operating system. Otherwise, it can be installed from source tarball as follows:
- Download and extractthetarballextractthetarball the tarball pyglet-1.1.4.tar.gz or a later version.
- Make sure that python is a recognizable command in shell. Otherwise, set the PYTHONPATH environment variable to the correct Python executable path.
- In a shell window, change to the mentioned extracted directory and then run the following command:
python setup.py install
- Review the succeeding installation instructions using the readme/install instruction files in the Pyglet source tarball.
If you have the package setuptools (http://pypi.python.org/pypi/setuptools) the Pyglet installation should be very easy. However, for this, you will need a runtime egg of Pyglet. But the egg file for Pyglet is not available at http://pypi.python.org. If you get hold of a Pyglet egg file, it can be installed by running the following command on Linux or Mac OS X. You will need administrator access to install the package:
$sudo easy_install -U pyglet
Summary of installation prerequisites
Linux/Unix/OS X platforms
2.6.4 (or any 2.6.x)
Install using binary distribution
Install from binary; also install additional developer packages (For example, with python-devel in the package name in a rpm-based Linux distribution).
Build and install from the source tarball.
1.1.4 or later
Install using binary distribution (the .msi file)
Mac: Install using disk image file (.dmg file).
Linux: Build and install using the source tarball.
Testing the installation
Before proceeding further, ensure that Pyglet is installed properly. To test this, just start Python from the command line and type the following:
If this import is successful, we are all set to go!
A primer on Pyglet
Pyglet provides an API for multimedia application development using Python. It is an OpenGL-based library that works on multiple platforms. It is primarily used for developing gaming and other graphically-rich applications. We will cover some important aspects of Pyglet framework.
We will briefly discuss some of the important modules and packages of Pyglet that we will use. Note that this is just a tiny chunk of the Pyglet framework. Please review the Pyglet documentation to know more about its capabilities, as this is beyond the scope of this article.
The pyglet.window.Window module provides the user interface. It is used to create a window with an OpenGL context. The Window class has API methods to handle various events such as mouse and keyboard events. The window can be viewed in normal or full screen mode. Here is a simple example of creating a Window instance. You can define a size by specifying width and height arguments in the constructor.
win = pyglet.window.Window()
The background color for the image can be set using OpenGL call glClearColor, as follows:
pyglet.gl.glClearColor(1, 1, 1, 1)
This sets a white background color. The first three arguments are the red, green, and blue color values. Whereas, the last value represents the alpha. The following code will set up a gray background color.
pyglet.gl.glClearColor(0.5, 0.5, 0.5, 1)
The following illustration shows a screenshot of an empty window with a gray background color.
The pyglet.image module enables the drawing of images on the screen. The following code snippet shows a way to create an image and display it at a specified position within the Pyglet window.
img = pyglet.image.load('my_image.bmp')
x, y, z = 0, 0, 0
img.blit(x, y, z)
A later section will cover some important operations supported by the pyglet.image module.
This is another important module. It is used to display an image or an animation frame within a Pyglet window discussed earlier. It is an image instance that allows us to position an image anywhere within the Pyglet window. A sprite can also be rotated and scaled. It is possible to create multiple sprites of the same image and place them at different locations and with different orientations inside the window.
Animation module is a part of pyglet.image package. As the name indicates, pyglet.image.Animation is used to create an animation from one or more image frames. There are different ways to create an animation. For example, it can be created from a sequence of images or using AnimationFrame objects. An animation sprite can be created and displayed within the Pyglet window.
This creates a single frame of an animation from a given image. An animation can be created from such AnimationFrame objects. The following line of code shows an example.
animation = pyglet.image.Animation(anim_frames)
anim_frames is a list containing instances of AnimationFrame.
Among many other things, this module is used for scheduling functions to be called at a specified time. For example, the following code calls a method moveObjects ten times every second.
Displaying an image
In the Image sub-section, we learned how to load an image using image.blit. However, image blitting is a less efficient way of drawing images. There is a better and preferred way to display the image by creating an instance of Sprite. Multiple Sprite objects can be created for drawing the same image. For example, the same image might need to be displayed at various locations within the window. Each of these images should be represented by separate Sprite instances. The following simple program just loads an image and displays the Sprite instance representing this image on the screen.
1 import pyglet
3 car_img= pyglet.image.load('images/car.png')
4 carSprite = pyglet.sprite.Sprite(car_img)
5 window = pyglet.window.Window()
6 pyglet.gl.glClearColor(1, 1, 1, 1)
9 def on_draw():
On line 3, the image is opened using pyglet.image.load call. A Sprite instance corresponding to this image is created on line 4. The code on line 6 sets white background for the window. The on_draw is an API method that is called when the window needs to be redrawn. Here, the image sprite is drawn on the screen. The next illustration shows a loaded image within a Pyglet window.
In various examples in this article, the file path strings are hardcoded. We have used forward slashes for the file path. Although this works on Windows platform, the convention is to use backward slashes. For example, images/car.png is represented as images\car.png. Additionally, you can also specify a complete path to the file by using the os.path.join method in Python. Regardless of what slashes you use, the os.path.normpath will make sure it modifies the slashes to fit to the ones used for the platform. The use of oos.path.normpath is illustrated in the following snippet:
original_path = 'C:/images/car.png"
new_path = os.path.normpath(original_path)
The preceding image illustrates Pyglet window showing a still image.
Mouse and keyboard controls
The Window module of Pyglet implements some API methods that enable user input to a playing animation. The API methods such as on_mouse_press and on_key_press are used to capture mouse and keyboard events during the animation. These methods can be overridden to perform a specific operation.
Adding sound effects
The media module of Pyglet supports audio and video playback. The following code loads a media file and plays it during the animation.
1 background_sound = pyglet.media.load(
The second optional argument provided on line 3 decodes the media file completely in the memory at the time the media is loaded. This is important if the media needs to be played several times during the animation. The API method play() starts streaming the specified media file.
eBook Price: $26.99
Book Price: $44.99
(For more resources on Python, see here.)
Animations with Pyglet
The Pyglet framework provides a number of modules required to develop animations. Lets now learn techniques to create 2D animations using Pyglet.
Viewing an existing animation
If you already have an animation in, for example, .gif file format, it can be loaded and displayed directly with Pyglet. The API method to use here is pyglet.image.load_animation.
Time for action – viewing an existing animation
This is going to be a short exercise. The goal of this section is to develop a primary understanding on use of Pyglet for viewing animations. So let's get on with it.
- Download the file SimpleAnimation.py from the Packt website. Also download the file SimpleAnimation.gif and place it in a sub-directory images. The code is illustrated as follows:
1 import pyglet
3 animation = pyglet.image.load_animation(
6 # Create a sprite object as an instance of this animation.
7 animSprite = pyglet.sprite.Sprite(animation)
9 # The main pyglet window with OpenGL context
10 w = animSprite.width
11 h = animSprite.height
12 win = pyglet.window.Window(width=w, height=h)
14 # r,g b, color values and transparency for the background
15 r, g, b, alpha = 0.5, 0.5, 0.8, 0.5
17 # OpenGL method for setting the background.
18 pyglet.gl.glClearColor(r, g, b, alpha)
20 # Draw the sprite in the API method on_draw of
21 # pyglet.Window
23 def on_draw():
The code is self-explanatory. On line 3, the API method image.load_animation creates an instance of class image.Animation using the specified animation file. For this animation, a Sprite object is created on line 7. The Pyglet window created on line 12 will be used to display the animation. The size of this window is specified by the height and width of the animSprite. The background color for the window is set using OpenGL call glClearColor.
- Next, we need to draw this animation sprite into the Pyglet window. The pyglet.window defines API method on_draw which gets called when an event occurs. The call to the draw() method of animation Sprite is made on line 25 to render the animation on screen. The code on line 22 is important. The decorator, @win.event allows us to modify the on_draw API method of pyglet.window.Window when an event occurs. Finally code on line 27 runs this application.
You can create your own animation file like SimpleAnimation.gif using freely available image editing software packages like GIMP. This animation file was created using GIMP 2.6.7, by drawing each of the characters on a separate layer and then blending all the layers using Filters | Animation | Blend.
- Put the file SimpleAnimation.py along with the animation file SimpleAnimation.gif in the same directory and then run the program as follows:
This will show the animation in a Pyglet window. You can use a different animation file instead of SimpleAnimation.gif. Just modify the related code in this file or add code to accept any GIF file as a command-line argument for this program. The next illustration shows some of the frames from this animation at different time intervals.
The preceding image is a screen capture of a running animation at different time intervals.
What just happened?
We worked out an example where an already created animation file was loaded and viewed using Pyglet. This short exercise taught us some preliminary things about viewing animations using Pyglet. For example, we learned how to create a Pyglet window and load an animation using pyglet.Sprite object. These fundamentals will be used throughout this article.
Animation using a sequence of images
The API method Animation.from_image_sequence enables creation of an animation using a bunch of sequential images. Each of the images is displayed as a frame in the animation, one after the other. The time for which each frame is displayed can be specified as an argument while creating the animation object. It can also be set after the animation instance is created.
Time for action – animation using a sequence of images
Let's develop a tool that can create an animation and display it on the screen. This tool will create and display the animation using the given image files. Each of the image files will be displayed as a frame in the animation for a specified amount of time. This is going to be a fun little animation that shows a grandfather clock with a pendulum. We will animate the pendulum oscillations with other things, including making the dial remaining still. This animation has only three image frames; two of them show the pendulum at opposite extremes. These images are sequenced as shown in the next illustration.
Clock image frames to be animated appear in the preceding image.
- Download the file ImageSequenceAnimation.py from the Packt website.
- The code in this file is presented below.
1 import pyglet
3 image_frames = ('images/clock1.png',
7 # Create the list of pyglet images
8 images = map(lambda img: pyglet.image.load(img),
11 # Each of the image frames will be displayed for 0.33
12 # seconds
13 # 0.33 seconds chosen so that the 'pendulam in the clock
14 # animation completes one oscillation in ~ 1 second !
16 animation = pyglet.image.Animation.from_image_sequence(
17 images, 0.33)
18 # Create a sprite instance.
19 animSprite = pyglet.sprite.Sprite(animation)
21 # The main pyglet window with OpenGL context
22 w = animSprite.width
23 h = animSprite.height
24 win = pyglet.window.Window(width=w, height=h)
26 # Set window background color to white.
27 pyglet.gl.glClearColor(1, 1, 1, 1)
29 # The @win.event is a decorator that helps modify the API
30 # methods such as
31 # on_draw called when draw event occurs.
33 def on_draw():
The tuple, image_frames contains the paths for the images. The map function call on line 8 creates pyglet.image objects corresponding to each of the image paths and stores the resultant images in a list. On line 16, the animation is created using the API method Animation.from_image_sequence. This method takes the list of image objects as an argument. The other optional argument is the time in seconds for which each of the frames will be shown. We set this time as 0.33 seconds per image so that the total time for a complete animation loop is nearly 1 second. Thus, in the animation, one complete oscillation of the pendulum will be complete in about one second. We already discussed the rest of the code in an earlier section.
- Place the image files in a sub-directory images within the directory in which file ImageSequenceAnimation.py is placed. Then run the program using:
You will see a clock with an oscillating pendulum in the window. The animation will continue in a loop and closing the window will end it.
What just happened?
By rapidly displaying still images, we just created something like a 'flipbook' cartoon! We developed a simple utility that takes a sequence of images as an input and creates an animation using Pyglet. To accomplish this task, we used Animation.from_image_sequence to create the animation and re-used most of the framework from the Viewing an existing animation section.
We learned a lot in this article about creating 2D animations in Python using Pyglet. Specifically, we:
- Learned some fundamental components of the Pyglet framework for creating animations. Modules such as Window, Image, Animation, Sprite, AnimationFrame, ImageGrid , and so on were discussed.
- Wrote code to create an animation using a sequence of images.
In the next article Python Multimedia: Animations Examples using Pyglet, we will work on some exciting projects such as animating a car riding in a thunderstorm, a 'bowling animation' with keyboard controls, and so on.
- Python Multimedia: Animations Examples using Pyglet [Article]
- Python Multimedia: Working with Audios [Article]
- Python 3: When to Use Object-oriented Programming [Article]
- Python 3 Object Oriented Programming: Managing objects [Article]
eBook Price: $26.99
Book Price: $44.99
About the Author :
Ninad has more than 6 years of experience in software design and development. He is currently working at IBM India. Prior to IBM, he was a Systems Programmer at Nanorex Inc. based in Michigan, USA. At Nanorex, he was involved in the development of an open source, interactive 3D CAD software, written in Python and C. This is where he developed his passion for the Python programming language. Besides programming, his favorite hobbies are reading and traveling. Ninad holds a Master's of Science degree in Mechanical Engineering from Kansas State University, USA.