Python GUI Programming Cookbook - Sample Chapter
Python GUI Programming Cookbook - Sample Chapter
ee
Over the course of the book, you will develop an entire GUI application, building recipe upon recipe
and connecting the GUI to a database. You will learn how to use threading to ensure your GUI doesn't
go unresponsive.
By the end of the book, you will be in Python GUI programming for developing a common
set of GUI applications.
to a database
and problems
problems efficiently
real-world problems
$ 44.99 US
28.99 UK
Burkhard Meier
P U B L I S H I N G
This book follows a task-based approach to help you create beautiful and very effective GUIs with the least
amount of code. It uses the simplest programming style to create a GUI in Python, and then moves on to
cover using object-oriented programming in later chapters.
pl
e
P U B L I S H I N G
Sa
Burkhard Meier
Preface
In this book, we will explore the beautiful world of graphical user interfaces (GUIs) using the
Python programming language.
Along the way, we will talk to networks, queues, the OpenGL graphical library, and many
more technologies.
This is a programming cookbook. Every chapter is self-contained and explains a certain
programming solution.
We will start very simply, yet throughout this book we will build a working program written
in Python 3.
We will also apply some design patterns and use best practices throughout this book.
The book assumes that the reader has some basic experience using the Python
programming language, but that is not really required to use this book.
If you are an experienced programmer in any programming language, you will have a fun
time extending your skills to programming GUIs using Python!
Are you ready?
Let's start on our journey
Preface
Chapter 3, Look and Feel Customization, shows several examples of how to create a good
"look and feel" GUI. On a practical level, we will add functionality to the Help | About menu
item we created in one of the recipes.
Chapter 4, Data and Classes, discusses saving the data our GUI displays. We will start using
object-oriented programming (OOP) in order to extend Python's built-in functionality.
Chapter 5, Matplotlib Charts, explains how to create beautiful charts that visually represent
data. Depending upon the format of the data source, we can plot one or several columns of
data within the same chart.
Chapter 6, Threads and Networking, explains how to extend the functionality of our Python
GUI using threads, queues, and network connections. This will show us that our GUI is not
limited at all to the local scope of our PC.
Chapter 7, Storing Data in Our MySQL Database via Our GUI, shows us how to connect to a
MySQL database server. The first recipe in this chapter will show how to install the free MySQL
Server Community Edition, and in the following recipes we will create databases, tables, and
then load data into those tables as well as modify these data. We will also read the data back
out from the MySQL server into our GUI.
Chapter 8, Internationalization and Testing, shows how to internationalize our GUI by
displaying text on labels, buttons, tabs, and other widgets in different languages. We will
start simple and then explore how we can prepare our GUI for internationalization at the
design level. We will also explore several ways to automatically test our GUI using Python's
built-in unit testing framework.
Chapter 9, Extending Our GUI with the wxPython Library, introduces another Python GUI
toolkit that currently does not ship with Python. It is called wxPython, and we will be using
the Phoenix version of wxPython which was designed to work well with Python 3.
Chapter 10, Creating Amazing 3D GUIs with PyOpenGL and PyGLet, shows how to transform
our GUI by giving it true three-dimensional capabilities. We will use two Python third-party
packages. PyOpenGL is a Python binding to the OpenGL standard, which is a graphics library
that comes built-in with all major operating systems. This gives the resulting widgets a native
look and feel. PyGLet is one such binding that we will explore in this chapter.
Chapter 11, Best Practices, explores different best practices that can help us to build our
GUI in an efficient way and keep it both maintainable and extendible. Best practices are
applicable to any good code and our GUI is no exception to designing and implementing
good software practices.
Introduction
In this chapter, we will develop our first GUI in Python. We start with the minimum code
required to build a running GUI application. Each recipe then adds different widgets to
the GUI form.
In the first two recipes, we show the entire code, consisting of only a few lines of code. In the
following recipes we only show the code to be added to the previous recipes.
Getting ready
To follow this recipe, a working Python development environment is a prerequisite. The IDLE
GUI that ships with Python is enough to start. IDLE was built using tkinter!
All the recipes in this book were developed using Python 3.4 on a Windows 7
64-bit OS. They have not been tested on any other configuration. As Python
is a cross-platform language, the code from each recipe is expected to run
everywhere.
If you are using a Mac, it does come built-in with Python, yet it might be missing
some modules such as tkinter, which we will use throughout this book.
We are using Python 3 and the creator of Python intentionally chose not to
make it backwards compatible with Python 2.
If you are using a Mac or Python 2, you might have to install Python 3 from
www.python.org in order to successfully run the recipes in this book.
How to do it...
Here are the four lines of Python code required to create the resulting GUI:
import tkinter as tk
win = tk.Tk()
win.title("Python GUI")
win.mainloop()
#
#
#
#
1
2
3
4
Chapter 1
Execute this code and admire the result:
How it works...
In line 1, we import the built-in tkinter module and alias it as tk to simplify our Python code.
In line 2, we create an instance of the Tk class by calling its constructor (the parentheses
appended to Tk turn the class into an instance). We are using the alias tk so we don't have to
use the longer word tkinter. We are assigning the class instance to a variable named win
(short for a window). As Python is a dynamically typed language, we did not have to declare
this variable before assigning to it and we did not have to give it a specific type. Python infers
the type from the assignment of this statement. Python is a strongly typed language, so every
variable always has a type. We just don't have to specify its type beforehand like in other
languages. This makes Python a very powerful and productive language to program in.
A little note about classes and types:
In Python every variable always has a type. We cannot create a variable
without assigning it a type. Yet, in Python, we do not have to declare the
type beforehand, as we have to do in the C programming language.
Python is smart enough to infer the type. At the time of writing, C# also
has this capability.
Using Python, we can create our own classes using the class keyword
instead of the def keyword.
In order to assign the class to a variable, we first have to create an
instance of our class. We create the instance and assign this instance
to our variable.
class AClass(object):
print('Hello from AClass')
classInstance = AClass()
There's more...
This recipe used a minimum amount of Python code to create our first GUI program. However,
throughout this book, we will use OOP when it makes sense.
How to do it...
We are preventing the GUI from being resized.
import tkinter as tk
# 1 imports
win = tk.Tk()
win.title("Python GUI")
# 2 Create instance
# 3 Add a title
win.resizable(0, 0)
win.mainloop()
# 5 Start GUI
Chapter 1
Running the code creates this GUI:
How it works...
Line 4 prevents the Python GUI from being resized.
Running this code will result in a GUI similar to the one we created in Recipe 1. However, the
user can no longer resize it. Also, notice how the maximize button in the toolbar of the window
is grayed out.
Why is this important? Because, once we add widgets to our form, resizing can make our GUI
look not as good as we want it to be. We will add widgets to our GUI in the next recipes.
Resizable() is a method of the Tk() class and, by passing in (0, 0), we prevent the GUI
from being resized. If we pass in other values, we hard-code the x and y start up size of the
GUI, but that won't make it nonresizable.
We also added comments to our code in preparation for the recipes contained in this book.
In visual programming IDEs such as Visual Studio .NET, C# programmers
often do not think of preventing the user from resizing the GUI they
developed in this language. That creates inferior GUIs. Adding this one line
of Python code can make our users appreciate our GUI.
How to do it...
In order to add a Label widget to our GUI, we are importing the ttk module from tkinter.
Please note the two import statements.
# imports
import tkinter as tk
from tkinter import ttk
# 1
# 2
# 3
Add the following code just above win.mainloop() located at the bottom of recipes 1 and 2.
# Adding a Label
# 4
ttk.Label(win, text="A Label").grid(column=0, row=0) # 5
How it works...
In line 3 of the above code, we are importing a separate module from tkinter. The ttk
module has some advanced widgets that make our GUI look great. In a sense, ttk is an
extension within tkinter.
We still need to import tkinter itself, but we have to specify that we now want to also use
ttk from tkinter.
ttk stands for 'themed tk". It improves our GUI look and feel.
Chapter 1
Line 5 above adds the label to the GUI, just before we call mainloop (not shown here to
preserve space. See recipes 1 or 2).
We are passing our window instance into the ttk.Label constructor and setting the text
property. This becomes the text our Label will display.
We are also making use of the grid layout manager, which we'll explore in much more depth
in Chapter 2, Layout Management.
Note how our GUI suddenly got much smaller than in previous recipes.
The reason why it became so small is that we added a widget to our form. Without a widget,
tkinter uses a default size. Adding a widget causes optimization, which generally means
There's more...
Try resizing and maximizing this GUI with a label and watch what happens.
How to do it...
We are adding a button that, when clicked, performs an action. In this recipe, we will update
the label we added in the previous recipe, as well as updating the text property of the button.
# Modify adding a Label
aLabel = ttk.Label(win, text="A Label")
aLabel.grid(column=0, row=0)
# 1
# 2
# 3
# 4
# 5
# Adding a Button
action = ttk.Button(win, text="Click Me!", command=clickMe)
action.grid(column=1, row=0)
# 6
# 7
# 8
After clicking the button, the color of the label has been changed, and so has the text of the
button. Action!
How it works...
In line 2 we are now assigning the label to a variable and in line 3 we use this variable to
position the label within the form. We will need this variable to change its properties in the
clickMe() function. By default, this is a module-level variable so we can access it inside
the function as long as we declare the variable above the function that calls it.
Line 5 is the event handler that is being invoked once the button gets clicked.
In line 7, we create the button and bind the command to the clickMe() function.
GUIs are event-driven. Clicking the button creates an event. We bind
what happens when this event occurs in the callback function using the
command property of the ttk.Button widget. Notice how we do not
use parentheses; only the name clickMe.
We also change the text of the label to include red as in the printed book, this might otherwise
not be obvious. When you run the code you can see that the color did indeed change.
Lines 3 and 8 both use the grid layout manager, which will be discussed in the following
chapter. This aligns both the label and the button.
Chapter 1
There's more...
We will continue to add more and more widgets to our GUI and we will make use of many
built-in properties in other recipes in the book.
Getting ready
This recipe builds upon the Creating buttons and changing their text property recipe.
How to do it...
# Modified Button Click Function
# 1
def clickMe():
# 2
action.configure(text='Hello ' + name.get())
# Position Button in second row, second column (zero-based)
action.grid(column=1, row=1)
# Changing our Label
# 3
ttk.Label(win, text="Enter a name:").grid(column=0, row=0) # 4
# Adding a Textbox Entry widget
# 5
name = tk.StringVar()
# 6
nameEntered = ttk.Entry(win, width=12, textvariable=name) # 7
nameEntered.grid(column=0, row=1) # 8
How it works...
In line 2 we are getting the value of the Entry widget. We are not using OOP yet, so how
come we can access the value of a variable that was not even declared yet?
Without using OOP classes, in Python procedural coding we have to physically place a name
above a statement that tries to use that name. So how come this works (it does)?
The answer is that the button click event is a callback function, and by the time the button
is clicked by a user, the variables referenced in this function are known and do exist.
Life is good.
Line 4 gives our label a more meaningful name, because now it describes the textbox below
it. We moved the button down next to the label to visually associate the two. We are still using
the grid layout manager, to be explained in more detail in Chapter 2, Layout Management.
Line 6 creates a variable name. This variable is bound to the Entry and, in our clickMe()
function, we are able to retrieve the value of the Entry box by calling get() on this variable.
This works like a charm.
Now we see that while the button displays the entire text we entered (and more), the textbox
Entry widget did not expand. The reason for this is that we had hard-coded it to a width of
12 in line 7.
Python is a dynamically-typed language and infers the type from the
assignment. What this means is if we assign a string to the variable name,
the variable will be of the type string, and if we assign an integer to name,
this variable's type will be integer.
Using tkinter, we have to declare the variable name as the type
tk.StringVar() before we can use it successfully. The reason is this
that Tkinter is not Python. We can use it from Python but it is not the
same language.
10
Chapter 1
Getting ready
This recipe extends the previous recipe.
How to do it...
Python is truly great. All we have to do to set the focus to a specific control when the GUI
appears is call the focus() method on an instance of a tkinter widget we previously
created. In our current GUI example, we assigned the ttk.Entry class instance to a
variable we named nameEntered. Now we can give it the focus.
Place the following code just above the bottom of the module that starts the main windows
event loop, just like in previous recipes. If you get some errors, make sure you are placing
calls to variables below the code where they are declared. We are not using OOP as of yet,
so this is still necessary. Later, it will no longer be necessary to do this.
nameEntered.focus()
On a Mac, you might have to set the focus to the GUI window first before being able to set the
focus to the Entry widget in this window.
Adding this one line of Python code places the cursor into our text Entry box, giving the
text Entry box the focus. As soon as the GUI appears, we can type into this text box without
having to click it first.
Note how the cursor now defaults to residing inside the text Entry box.
11
After adding the above line of Python code, clicking the button no longer creates any action!
How it works...
This code is self-explanatory. We set the focus to one control and disable another widget.
Good naming in programming languages helps to eliminate lengthy explanations. Later in
this book, there will be some advanced tips on how to do this while programming at work or
practicing our programming skills at home.
There's more...
Yes. This is only the first chapter. There is much more to come.
Getting ready
This recipe extends the previous recipes.
How to do it...
We are inserting another column between the Entry widget and the Button using the grid
layout manager. Here is the Python code.
ttk.Label(win, text="Choose a number:").grid(column=1, row=0) # 1
number = tk.StringVar()
# 2
numberChosen = ttk.Combobox(win, width=12, textvariable=number) #3
12
Chapter 1
numberChosen['values'] = (1, 2, 4, 42, 100)
numberChosen.grid(column=1, row=1)
numberChosen.current(0)
# 4
# 5
# 6
This code, when added to previous recipes, creates the following GUI. Note how, in line 4 in
the preceding code, we assign a tuple with default values to the combo box. These values
then appear in the drop-down box. We can also change them if we like (by typing in different
values when the application is running).
How it works...
Line 1 adds a second label to match the newly created combo box (created in line 3). Line 2
assigns the value of the box to a variable of a special tkinter type (StringVar), as we did
in a previous recipe.
Line 5 aligns the two new controls (label and combo box) within our previous GUI layout, and
line 6 assigns a default value to be displayed when the GUI first becomes visible. This is the
first value of the numberChosen['values'] tuple, the string "1". We did not place quotes
around our tuple of integers in line 4, but they got casted into strings because, in line 2, we
declared the values to be of type tk.StringVar.
The screenshot shows the selection made by the user (42). This value gets assigned to the
number variable.
There's more...
If we want to restrict the user to only be able to select the values we have programmed into
the Combobox, we can do that by passing the state property into the constructor. Modify line
3 in the previous code to:
numberChosen = ttk.Combobox(win, width=12, textvariable=number,
state='readonly')
13
After choosing a number, entering a name, and then clicking the button, we get the following
GUI result, which now also displays the number selected:
Getting ready
This recipe extends the previous recipes.
How to do it...
We are creating three Checkbutton widgets that differ in their states. The first is disabled
and has a checkmark in it. The user cannot remove this checkmark as the widget is disabled.
The second Checkbutton is enabled and, by default, has no checkmark in it, but the user
can click it to add a checkmark.
The third Checkbutton is both enabled and checked by default. The users can uncheck
and recheck the widget as often as they like.
# Creating three checkbuttons
# 1
chVarDis = tk.IntVar()
# 2
check1 = tk.Checkbutton(win, text="Disabled", variable=chVarDis, state
='disabled')
# 3
check1.select()
# 4
14
Chapter 1
check1.grid(column=0, row=4, sticky=tk.W) # 5
chVarUn = tk.IntVar()
# 6
check2 = tk.Checkbutton(win, text="UnChecked", variable=chVarUn)
check2.deselect()
# 8
check2.grid(column=1, row=4, sticky=tk.W) # 9
chVarEn = tk.IntVar()
# 10
check3 = tk.Checkbutton(win, text="Enabled", variable=chVarEn)
check3.select()
# 12
check3.grid(column=2, row=4, sticky=tk.W) # 13
How it works...
In lines 2, 6, and 10, we create three variables of type IntVar. In the following line, for each
of these variables we create a Checkbutton, passing in these variables. They will hold the
state of the Checkbutton (unchecked or checked). By default, that is either 0 (unchecked)
or 1 (checked) so the type of the variable is a tkinter integer.
We place these Checkbutton widgets in our main window so the first argument passed into
the constructor is the parent of the widget; in our case win. We give each Checkbutton a
different label via its text property.
Setting the sticky property of the grid to tk.W means that the widget will be aligned to the
west of the grid. This is very similar to Java syntax and it means that it will be aligned to the
left. When we resize our GUI, the widget will remain on the left side and not be moved towards
the center of the GUI.
Lines 4 and 12 place a checkmark into the Checkbutton widget by calling the select()
method on these two Checkbutton class instances.
We continue to arrange our widgets using the grid layout manager, which will be explained in
more detail in Chapter 2, Layout Management.
15
Getting ready
This recipe extends the previous recipes.
How to do it...
We are adding the following code to the previous recipe:
# Radiobutton Globals
COLOR1 = "Blue"
COLOR2 = "Gold"
COLOR3 = "Red"
#
#
#
#
1
2
3
4
# Radiobutton Callback # 5
def radCall():
# 6
radSel=radVar.get()
if
radSel == 1: win.configure(background=COLOR1)
elif radSel == 2: win.configure(background=COLOR2)
elif radSel == 3: win.configure(background=COLOR3)
# create three Radiobuttons
# 7
radVar = tk.IntVar()
# 8
rad1 = tk.Radiobutton(win, text=COLOR1, variable=radVar, value=1,
command=radCall)
# 9
rad1.grid(column=0, row=5, sticky=tk.W) # 10
rad2 = tk.Radiobutton(win, text=COLOR2, variable=radVar, value=2, comm
and=radCall)
# 11
rad2.grid(column=1, row=5, sticky=tk.W) # 12
rad3 = tk.Radiobutton(win, text=COLOR3, variable=radVar, value=3, comm
and=radCall)
# 13
rad3.grid(column=2, row=5, sticky=tk.W) # 14
16
Chapter 1
Running this code and selecting the Radiobutton named Gold creates the following window:
How it works...
In lines 2-4 we create some module-level global variables, which we will use in the creation of
each radio button as well as in the callback function that creates the action of changing the
background color of the main form (using the instance variable win).
We are using global variables to make it easier to change the code. By assigning the name of
the color to a variable and using this variable in several places, we can easily experiment with
different colors. Instead of doing a global search-and-replace of a hard-coded string (which is
prone to errors), we just need to change one line of code and everything else will work. This is
known as the DRY principle, which stands for Don't Repeat Yourself. This is an OOP concept
that we will use in later recipes of the book.
The names of the colors we are assigning to the variables (COLOR1, COLOR2
) are tkinter keywords (technically, they are symbolic names). If we use
names that are not tkinter color keywords, then the code will not work.
Line 6 is the callback function that changes the background of our main form (win)
depending upon the user's selection.
In line 8 we are creating a tk.IntVar variable. What is important about this is that we are
creating only one variable to be used by all three radio buttons. As can be seen from the
above screenshot, no matter which Radiobutton we select, all the others will automatically
be unselected for us.
Lines 9 to 14 create the three radio buttons, assign them to the main form, and pass in
the variable to be used in the callback function that creates the action of changing the
background of our main window.
While this is the first recipe that changes the color of a widget, quite
honestly, it looks a bit ugly. A large portion of the following recipes in
this book explain how to make our GUI look truly amazing.
17
There's more...
Here is a small sample of the available symbolic color names that you can look up at the
official tcl manual page:
http://www.tcl.tk/man/tcl8.5/TkCmd/colors.htm
Name
alice blue
AliceBlue
Blue
Gold
Red
Red
240
240
0
255
255
Green
248
248
0
215
0
Blue
255
255
255
0
0
Some of the names create the same color, so alice blue creates the same color as
AliceBlue. In this recipe we used the symbolic names Blue, Gold, and Red.
Getting ready
This recipe extends the previous recipes. You can download the code for each chapter of this
book from the Packt Publishing website.
How to do it...
By adding the following lines of code, we create a ScrolledText widget:
# Add this import to the top of the Python Module
from tkinter import scrolledtext
# 2
# Using a scrolled Text control
scrolW = 30
scrolH = 3
18
# 3
# 4
# 5
# 1
Chapter 1
scr = scrolledtext.ScrolledText(win, width=scrolW, height=scrolH,
wrap=tk.WORD)
# 6
scr.grid(column=0, columnspan=3)
# 7
We can actually type into our widget, and if we type enough words, the lines will automatically
wrap around!
Once we type in more words than the height of the widget can display, the vertical scrollbar
becomes enabled. This all works out-of-the-box without us needing to write any more code
to achieve this.
How it works...
In line 2 we are importing the module that contains the ScrolledText widget class.
Add that to the top of the module, just below the other two import statements.
Lines 4 and 5 define the width and height of the ScrolledText widget we are about
to create. These are hard-coded values we are passing into the ScrolledText widget
constructor in line 6.
These values are magic numbers found by experimentation to work well. You might
experiment by changing srcolW from 30 to 50 and observe the effect!
19
Getting ready
We are refactoring some parts of the previous recipe's code, so you need that code to apply
to this recipe to.
How to do it...
# First, we change our Radiobutton global variables into a list.
colors = ["Blue", "Gold", "Red"]
# 1
# create three Radiobuttons using one variable
radVar = tk.IntVar()
Next we are selecting a non-existing index value for radVar.
radVar.set(99)
# 2
Now we are creating all three Radiobutton widgets within one loop.
for col in range(3):
# 3
curRad = 'rad' + str(col)
curRad = tk.Radiobutton(win, text=colors[col],
variable=radVar,
value=col, command=radCall)
20
Chapter 1
curRad.grid(column=col, row=5, sticky=tk.W)
Running this code will create the same window as before, but our code is much cleaner and
easier to maintain. This will help us when we expand our GUI in the following recipes.
How it works...
In line 1, we have turned our global variables into a list.
In line 2, we are setting a default value to the tk.IntVar variable we named radVar. This
is important because, while in the previous recipe we had set the value for Radiobutton
widgets starting at 1, in our new loop it is much more convenient to use Python's zero-based
indexing. If we did not set the default value to a value outside the range of our Radiobutton
widgets, one of the radio buttons would be selected when the GUI appears. While this in itself
might not be so bad, it would not trigger the callback and we would end up with a radio button
selected that does not do its job (that is, change the color of the main win form).
In line 3 we are replacing the three previously hard-coded creations of the Radiobutton
widgets with a loop, which does the same. It is just more concise (fewer lines of code)
and much more maintainable. For example, if we want to create 100 instead of just 3
Radiobutton widgets, all we have to change is the number inside Python's range operator.
We would not have to type or copy and paste 97 sections of duplicate code, just one number.
Line 4 shows the modified callback, which physically lives above the previous lines.
We placed it below to give emphasis to the more important parts of this recipe.
There's more...
This recipe concludes the first chapter of this book. All the following recipes in all of the next
chapters will build upon the GUI we have constructed so far, greatly enhancing it.
21
www.PacktPub.com
Stay Connected: