This book is a collection of code recipes for creating and animating graphic objects using the marvelous Python language. In order to create and manipulate graphic objects, Python makes use of the Tkinter module. The prerequisite for using Python and Tkinter is obviously to have both installed. Both are free and Open Source and instructions for obtaining and installing them are abundantly available on the web. Just Google phrases like "install Python" and you will be spoilt for choice.
Our first task is to prove that Python and Tkinter are installed and working on our computer. In this book, we use Python version 2.6. Python 3.0 which came out in 2010 requires some changes in syntax that we won't be using in this book.
Let's look at some simple tests to check if Python is installed. If we download and install Python on Windows, it automatically includes Tkinter as one of the essential modules so we do not need to acquire and install it separately.
We need a one line Python program that will prove that the Python interpreter is installed and working on our computer platform.
Create a folder (directory) called something like
constrfor short. You will place all your Python programs inside this directory. In a text editor such as gedit on Linux or notepad on Windows. If we are working in Windows, there is a nice editor called "Context" that can be downloaded for free from http://www.contexteditor.org/ Context, that is sensitive to Python syntax and has a search-and-replace function that is useful.
Type the following line:
Print 'My wereld is "my world" in Dutch'
Save this as a file named
simple_1.py, inside the directory called
Open up an X terminal or a DOS window if you are using MS Windows.
Change directory into
python simple_1.pyand your program will execute. The result should look like the following screenshot:
This proves that your Python interpreter works, your editor works, and that you understand all that is needed to run all the programs in this book. Congratulations.
""" Program name: simplest_1.py Objective: Print text to the screen. Keywords: text, simplest ========================= Printed "mywereld" on terminal. Author: Mike Ohlson de Fine """ Print 'mywereld is "my world" in Dutch'
Any instructions you type into a Linux X terminal or DOS terminal in MS Windows are treated as operating system commands. By starting these commands from within the same directory where your Python program is stored you do not have to tell the Python and operating system where to search for your code. You could store the code in another directory but you would then need to precede the program name with the path.
Try the longer version of the same basic print instructions shown in the following program.
All the text between the """ (triple quotation marks) is purely for the sake of good documentation and record keeping. It is for the use of programmers, and that includes you. Alas, the human memory is imperfect. Bitter experience will persuade you that it is wise to provide fairly complete information as a header in your programs as well as comments inside the program.
However, in the interest of saving space and avoiding distractions, these header comments have been left out in the rest of this book.
Here is a slightly longer version of the previous program. However, the following modules are commanded to "report for duty" inside our program even though they are not actually used at this time:
We need the assurance that all the Python modules we will be using later are present and accessible to Python, and therefore, to our code. Each module is a self-contained library of code functions and objects that are called frequently by the commands in your programs.
In a text editor type the lines given in the following code.
Save this as a file named
simple_2.py, inside the directory called
constras we did previously.
As before, open up an X terminal or a DOS window, if you are using MS Windows.
Change directory into
python simple_2.pyand our program should execute. The result should look like the following screenshot:
This proves that your Python interpreter can access the necessary library functions it will need.
""" Program name: simplest_2.py Objective: Send more than one line of text to the screen. Keywords: text, simple ====================================== Author: Mike Ohlson de Fine """ import Tkinter import math import random import time import tkFont print "=======================================" print "A simple, apparently useless program like this does useful things:" print "Most importantly it checks whether your Python interpreter and " print "the accompanying operating system environment works" print " - including hardware and software" print "======================================" print " No matter how simple it is always a thrill" print " to get your first program to run"
For example: print "
dog_name is the name of a variable used to store some data.
When you are writing a piece of Python code for the first time, you are often a bit unsure if your understanding of the logic is completely correct. So we would like to watch the progress of instruction execution in an exploratory way. It is a great help to be able to see that at least part of the code works. A major strength of Python is the way it takes our instructions one at a time and executes them progressively. It will only stop when the end is reached or a when programming flaw halts progress. If we have a twenty line program and only the first five lines are bug-free and the rest are unexecutable garbage, the Python interpreter will at least execute the first five. This is where the
This is how you use print and the Python interpreter. When we are having trouble with our code and it just won't work and we are battling to figure out why, we can just insert print statements at various chosen points in our program. This way you can get some intermediate values of variables as your own private status reports. When we want to switch off our print watchdogs we simply type a hash (
#) symbol in front, thus transforming them into passive comments. Later on, if you change your mind and want the prints to be active again you just remove the leading hash symbols.
In a text editor, type the code given below.
Save this as a file named
simple_line_1.py, inside the directory called
As before open up an X terminal or DOS window if you are using MS Windows.
Change directory into
python simple_line_1.pyand your program should execute. The command terminal result should look like the following screenshot:
The Tkinter canvas output should look like the following screenshot:
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> from Tkinter import * root = Tk() root.title('Very simple Tkinter line') canvas_1 = Canvas(root, width=300, height=200, background="#ffffff") canvas_1.grid(row=0, column=0) canvas_1.create_line(10,20 , 50,70) root.mainloop() #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
The start point is the first pair of numbers in
canvas_1.create_line(10,20 , 50,70).In another way, the start is given by the coordinates
y_start=20. The end point of the line is specified by the second pair of numbers
y_end=70. The units of measurement are pixels. A pixel is the smallest dot that can be displayed on our screen.
However, should you want to change color or thickness, you just do it by specifying the settings.
How do we create and execute a
.exe file that will run a compiled version of our Python and Tkinter programs? Can we make a self-contained folder that will run on an MS Windows or Linux distribution that uses a different version of Python from the ones we use? The answers to both questions are yes and the tool to achieve this is an Open Source program called
cx_Freeze. Often what we would like to do is have our working Python program on a memory stick or downloadable on a network and be able to demonstrate it to friends, colleagues, or clients without the need to download Python onto the client's system.
cx_Freeze allows us to create a distributable form of our Python graphic program.
You will need to download
cx_Freeze from http://cx-freeze.sourceforge.net/. We need to pick a version that has the same version number as the Python version we are using. Currently, there are versions available from version 2.4 up to 3.1.
MS Windows : Download
cx_Freeze-4.2.win32-py2.6.msi, the windows installer for Python 2.6. If we have another Python version, then we must choose the appropriate installer from http://cx-freeze.sourceforge.net/.
Save and run this installer.
On completion of a successful Windows install we will see a folder named
cx_Freeze inside \Python26\Lib\site-packages\.
If this does not work we may need to first install a development-capable version of Python by running the command
apt-get install python-dev. Then go back and repeat step 1.
Test for success by typing in
pythonin a command terminal to invoke the Python interpreter.
Then after the
import cx_Freeze. If the interpreter returns a new line and the
>>>prompt again, without any complaints, we have been successful.
#setup.py from cx_Freeze import setup, Executable setup(executables=[Executable("/constr/walking_birdy_1.py")])
Save it as
Then, in a command terminal run
python /constr/setup.py build
We will see a lot of system compilation commands scrolling down the command terminal that will eventually stop without error messages.
We will find our complete self-contained executable inside a folder named
build. Under Linux, we will find it inside our home directory under
/build/exe.linux-i686-2.6. Under MS Windows, we will find it inside
We just need to copy the folder
buildwith all its contents to wherever we want to run our self-contained program.
A word of caution. If we use external files like images inside our code, then the path addresses of the files must be absolute because they are coded into, or frozen, into the executable version of our Python program. There are ways of setting up search paths which can be read at http://cx-freeze.sourceforge.net/cx_Freeze.html.
example, say we want to use some
GIF images in our program and then demonstrate them on other computers. First we place a folder called, for example,
/birdy_pics, onto a USB memory stick. In the original program,
walking_birdy_1.py, make sure the path addresses to the images point to the
/birdy_pics folder on the stick. After compilation, copy the folder
build onto the USB memory stick. Now when we double-click on the executable
walking_birdy_1 it can locate the images on the USB memory stick when it needs to. These files include everything that is needed for your program, and you should distribute the whole directory contents to any user who wants to run your program without needing to install Python or Tkinter.