Page 69 - Programming the Raspberry Pi Getting Started with Python
P. 69
7
Graphical User Interfaces
Everything we have done so far has been text based. In fact, our Hangman game would not have
looked out of place on a 1980s home computer. This chapter shows you how to create applications
with a proper graphical user interface (GUI).
Tkinter
Tkinter is the Python interface to the Tk GUI system. Tk is not specific to Python; there are interfaces
to it from many different languages, and it runs on pretty much any operating system, including
Linux. Tkinter comes with Python, so there is no need to install anything. It is also the most
commonly used tool for creating a GUI for Python.
Hello World
Tradition dictates that the first program you write with a new language or system should do something
trivial, just to show it works! This usually means making the program display a message of “Hello
World.” As you’ll recall, we already did this for Python back in Chapter 3, so I’ll make no apologies
for starting with this program:
Figure 7-1 shows the rather unimpressive application.
Figure 7-1 Hello World in Tkinter
You don’t need to worry about how all this works. You do, however, need to know that you must
assign a variable to the object Tk. Here, we call this variable root, which is a common convention. We
then create an instance of the class Label, whose first argument is root. This tells Tkinter that the
label belongs to it. The second argument specifies the text to display in the label. Finally, the method
pack is called on the label. This tells the label to pack itself into the space available. The method pack
controls the layout of the items in the window. Shortly, we will use an alternative type of layout for
the components in a grid.
Temperature Converter
To get started with Tkinter, you’ll gradually build up a simple application that provides a GUI for
temperature conversion (see Figure 7-2). This application will use the converter module we created
in Chapter 5 to do the calculation.
Figure 7-2 A temperature conversion application
Our Hello World application, despite being simple, is not well structured and would not lend itself
well to a more complex example. It is normal when building a GUI with Tkinter to use a class to
represent each application window. Therefore, our first step is to make a framework in which to slot