Book Image

Python Game Programming By Example

Book Image

Python Game Programming By Example

Overview of this book

Table of Contents (14 chapters)
Python Game Programming By Example
About the Authors
About the Reviewers

The basic GUI layout

We will start out game by creating a top-level window as in the simple program we ran previously. However, this time, we will use two nested widgets: a container frame and the canvas where the game objects will be drawn, as shown here:

With Tkinter, this can easily be achieved using the following code:

import tkinter as tk

lives = 3
root = tk.Tk()
frame = tk.Frame(root)
canvas = tk.Canvas(frame, width=600, height=400, bg='#aaaaff')
root.title('Hello, Pong!')


Downloading the example code

You can download the example code files from your account at for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

Through the tk alias, we access the classes defined in the tkinter module, such as Tk, Frame, and Canvas.

Notice the first argument of each constructor call which indicates the widget (the child container), and the required pack() calls for displaying the widgets on their parent container. This is not necessary for the Tk instance, since it is the root window.

However, this approach is not exactly object-oriented, since we use global variables and do not define any new classes to represent our new data structures. If the code base grows, this can lead to poorly organized projects and highly coupled code.

We can start encapsulating the pieces of our game in this way:

import tkinter as tk

class Game(tk.Frame):
    def __init__(self, master):
        super(Game, self).__init__(master)
        self.lives = 3
        self.width = 610
        self.height = 400
        self.canvas = tk.Canvas(self, bg='#aaaaff',

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Hello, Pong!')
    game = Game(root)

Our new type, called Game, inherits from the Frame Tkinter class. The class Game(tk.Frame): definition specifies the name of the class and the superclass between parentheses.

If you are new to object-oriented programming with Python, this syntax may not sound familiar. In our first look at classes, the most important concepts are the __init__ method and the self variable:

  • The __init__ method is a special method that is invoked when a new class instance is created. Here, we set the object attributes, such as the width, the height, and the canvas widget. We also call the parent class initialization with the super(Game, self).__init__(master) statement, so the initial state of the Frame is properly initialized.

  • The self variable refers to the object, and it should be the first argument of a method if you want to access the object instance. It is not strictly a language keyword, but the Python convention is to call it self so that other Python programmers won't be confused about the meaning of the variable.

In the preceding snippet, we introduced the if __name__ == '__main__' condition, which is present in many Python scripts. This snippet checks the name of the current module that is being executed, and will prevent starting the main loop where this module was being imported from another script. This block is placed at the end of the script, since it requires that the Game class be defined.


New- and old-style classes

You may see the MySuperClass.__init__(self, arguments) syntax in some Python 2 examples, instead of the super call. This is the old-style syntax, the only flavor available up to Python 2.1, and is maintained in Python 2 for backward compatibility.

The super(MyClass, self).__init__(arguments) is the new-class style introduced in Python 2.2. It is the preferred approach, and we will use it throughout this book.

See the script, which contains this code. Since no external assets are needed, you can place it in any directory and execute it from the Python command line by running The main loop will run indefinitely until you click on the close button of the window, or you kill the process from the command line.

This is the starting point of our game, so let's start diving into the Canvas widget and see how we can draw and animate items in it.