Session 21 (CFM2103)

21.1 Introduction

In the last two sessions of CFM2103 we are going to explore GUI programming in Python by using the module tkinter.

GUI = Graphical User Interface

Computers interact with humans through user interfaces. Broadly speaking, such an interface consists of two parts: (i) hardware devices (keyboard + video display); (ii) the way the computer accepts commands from the user.

For example, we can use Spyder by typing commands in the console. The console is characterised by a prompt; users type commands, which are then executed. This is an example of a command line interface. In the early days of computing (pre-1980s) this was the only way for interacting with computers (e.g., if you wanted to open a file, the right "incantation" had to be entered using the keyboard....).

Graphical user interfaces (GUIs, for short) allow users to interact with a computer through graphical elements on the screen. This led to the introduction of the mouse as an input device: instead of typing commands on the keyboard, users can point at a graphical element and click the mouse to activate them.

Since GUI programs must respond to the actions of the user, it is said that they are event-driven, in the sense that the user causes events to take place (e.g., clicking of a button).

21.2 The tkinter module

Python comes with a module named tkinter that allows us to create GUI programs. The name 'tkinter' is short for 'Tk interface'; Tk is a GUI library used by many other programming languages.

A GUI program presents a window with various graphical widgets with which the user can interact or view. The tkinter module provides 15 widgets, which are described in the table below. It is beyond the scope of these sessions to provide an in-depth coverage of all the widgets listed there; we shall explore the basics of creating simple GUI programs that gather and display data.





Tkinter widgets

21.3 The first steps

We start with the simplest GUI program: our code will simply display an empty window. Later on, we are going to add labels (text) and buttons, and will learn how to customize them as well.

In [1]:
# This program displays an empty window.

import tkinter

def main():
    # Create the main window widget.
    main_window = tkinter.Tk()

    # Enter the tkinter main loop.
    tkinter.mainloop()

# Call the main function.
main()
  • Line 3 imports the tkinter module.
  • Line 7 creates an instance of tkinter modules's Tk class, and assigns it to a variable ('main_window' in this case; you can use whatever name you want, some programmers prefer the name 'root'). The object 'main_window' is the root widget, i.e. the main window in the program.
  • Line 10 calls the tkinter module's 'mainloop()' function. This function runs like an infinite loop until you close the main window.

GUI programs tend to have many lines of code and use a large number of functions. OOP provides a cleaner implementation by allowing a more modular approach. It is common practice to write a class with an __init__ method that builds the GUI. When an instance of this class is created, the GUI appears on the screen. An object-oriented version of our earlier code is included below:

In [2]:
# This program displays an empty window.
# OO implementation

import tkinter

class MyGUI:
    def __init__(self):
        self.main_window = tkinter.Tk()
        tkinter.mainloop()

# Create an instance of the MyGUI class.
my_gui = MyGUI()

For the purposes of this introduction we shall keep things simple and avoid the OO approach. Everything we do below (and in the next session) will be based on procedural programming. I'll also ignore the use of a 'main( )' function in order to make the code easier to read.

There are basically a few main steps involved in creating any custom GUI program (for some of the simpler programs listed on this page, some of these steps are irrelevant because the programs are very simple and have limited functionality):

  • Import from tkinter the modules you need (you may have additional import statements, depending on what your GUI is supposed to do).
  • Create instances of the widgets you want in your interface.
  • Define the location and size of each widget.
  • Create functions that will perform your desired actions on user-generated events (e.g., typing some text in a box, clicking a button, etc).
  • Connect your functions to specific events.
  • Start the GUI event-loop.

21.4 The 'Label' widgets

The 'Label' widget allows us to display a single line of text in the window that we created above.

To this end, we create an instance of the tkinter module's 'Label' class (line 7). On the next line this is then placed on the screen by using the pack() method -- the rest of the code below is the same as before.

In [3]:
# This program displays a label with text

import tkinter

main_window = tkinter.Tk()

label = tkinter.Label(main_window, text='Hello World!')
label.pack()

tkinter.mainloop()

Adding a widget to any type of window (root or otherwise) is always a two-step process. First, you have to create an instance of that widget by using the appropriate class. For example, above we used the (pre-defined) class 'Label' on line 7. Second, you need to make your widget visible on the screen; that's the role of line 8.

In tkinter there are two different ways to place stuff in a window. We have encountered the pack() method above; this is the simplest way, but it does not allow us much control as to where we want our label to appear in the window (we'll explore this further shortly). The other method is called grid(); with this method we have full control of the positioning of our graphical elements. We shall return to this aspect before the end of this section.

If we want to display several labels, we can do something like this:

In [4]:
# This program displays two labels with text.

import tkinter

main_window = tkinter.Tk()

label1 = tkinter.Label(main_window, text='Hello World!')
label2 = tkinter.Label(main_window, text='This is my first GUI!')
label1.pack()
label2.pack()
# you can add as many labels as you want.....

tkinter.mainloop()

Next, we illustrate how we can use pack() with one of its standard arguments:

In [5]:
# This program displays two labels with text.

import tkinter

main_window = tkinter.Tk()

label1 = tkinter.Label(main_window, text='Hello World!')
label2 = tkinter.Label(main_window, text='This is my first GUI!')
label1.pack(side="left")
label2.pack(side="left")
# you can add as many labels as you want.....

tkinter.mainloop()

On lines 9 and 10, we call each Label widget's 'pack()' method passing the argument side='left'. This specifies that the widget should be positioned as far left as possible inside the root widget. Because the 'label1' was added to the 'main_window' first, it will appear at the leftmost edge; the 'label2' widget was added next, so it appears next to the 'label1' widget. As a result, the labels end up side by side.

The valid 'side' arguments that you can pass to the pack() method are:

  • side='top'
  • side='bottom'
  • side='left'
  • side='right'
You should use the above code with these settings for the two labels, in order to get an intuitive feeling for what they do.

Before we close this section we are going to have a brief look at the other method available for placing widgets in the root window. The syntax for the 'grid()' method is the following:

NameOfWidget.grid(grid_options)


where you'll replace 'NameOfWidget' with the appropriate name (see the table at the top of this page). There are many options possible, here I'll mention only a few basic ones:

  • column = the column to put widget in; the default is 0 (leftmost column).
  • row = the row to put the widget in; the default is 0 (topmost).
  • relief = has two values: 'tk.RIDGE' or 'tk.SUNKEN' -- see example below.
In [6]:
import tkinter as tk

root = tk.Tk()
for ir in range(3):
    for ic in range(3):
        mylabel = tk.Label(root, text=str(ir) + ',' + str(ic), padx=20, pady=20)
        mylabel.grid(row=ir, column=ic)

root.mainloop()


Plain labels positioned with the 'grid( )' method
In [7]:
import tkinter as tk

root = tk.Tk()
for ir in range(3):
    for ic in range(3):
        mylabel = tk.Label(root, text=str(ir) + ',' + str(ic),\
                                             padx=20, pady=20,\
                                             relief=tk.SUNKEN)
        mylabel.grid(row=ir, column=ic)

root.mainloop()


Labels with the 'relief' option

21.5 Organising widgets with 'Frames'

A Frame is a container (in particular, a widget) that can hold other widgets. Frames can be used to organise the widgets in a window.

For example, we can place a set of Labels in one Frame, then place another set of Labels in a different Frame and arrange them in a different way. The Frames can then be positioned on the screen as we wish. This process is illustrated in the code included below:



Arrangement of widgets
In [61]:
# This program creates labels in two different frames. 
# (refer to the above sketch for the layout of our GUI)
import tkinter

main_window = tkinter.Tk()

# Create two frames, one for the top of the
# window, and one for the bottom:
top_frame = tkinter.Frame(main_window)
bottom_frame = tkinter.Frame(main_window)

# Create three Label widgets for
# the top frame:
label1 = tkinter.Label(top_frame, text='JANUARY')
label2 = tkinter.Label(top_frame, text='FEBRUARY')
label3 = tkinter.Label(top_frame, text='MARCH')

# Pack the labels that are in the top frame.
# Use the side='top' argument to stack them
# one on top of the other.
label1.pack(side='top')
label2.pack(side='top')
label3.pack(side='top')

# Create three Label widgets for 
# the bottom frame:
label4 = tkinter.Label(bottom_frame, text='JANUARY')
label5 = tkinter.Label(bottom_frame, text='FEBRUARY')
label6 = tkinter.Label(bottom_frame, text='MARCH')
        
# Pack the labels that are in the bottom frame.
# Use the side='left' argument to arrange them
# horizontally from the left of the frame.
label4.pack(side='left')
label5.pack(side='left')
label6.pack(side='left')

# Yes, we have to pack the frames too!
top_frame.pack()
bottom_frame.pack()

# Enter the tkinter main loop.
tkinter.mainloop()

Take a look at lines 9 and 10: 'top_frame' and 'bottom_frame' are the names of two variables that store two Frame objects. The first argument of the 'Frame()' function (i.e., 'main_window') indicate where the frames are to be placed.

Lines 14-16 create three Label widgets; note that these frames are to be added to the 'top_frame' widget. On lines 21-23 we call the 'pack()' method with the argument side='top' that causes the Label widgets to be stacked on top of each other inside the 'top_frame'.

Lines 27-29 create three more Label widgets; these are added to the 'bottom_frame' widget. On lines 34-36 we call the 'pack()' method for each of these, passing side='left' as an argument. This causes the three widgets to appear horizontally inside the Frame (the bottom one).

Frames also have to be "packed". Hence, on lines 39-40 the Frame widget's 'pack()' method is called, making the Frame widgets visible on the screen.

21.6 'Button' widgets

The Button widget is used to create a standard button in a window. When the user clicks a button, a specified function is called.

A callback function is a function that executes when the user clicks the button. When you create a 'Button' widget you can specify the text that is to appear on the face of the button and the name of the callback function.

The next code illustrates the above points. This program displays a simple window with a button. When the user clicks the button, the program launches a separate info dialog box.

In [47]:
#ButtonGUI

# This program demonstrates a Button widget.
# When the user clicks the Button, an
# info dialog box is displayed.

import tkinter
import tkinter.messagebox # must be imported for 
                          # the info dialog box

root = tkinter.Tk()

# Create the callback function:
def do_something():
    # Display an info dialog box.
    tkinter.messagebox.showinfo('Response', \
                                'Thanks for clicking the button.')

# Create a Button widget. The text 'Click Me!'
# should appear on the face of the Button. The
# do_something() function should be executed when
# the user clicks the Button:
button1 = tkinter.Button(root, \
                         text='Click Me!', \
                         command=do_something)

# Make the button visible on the screen.
button1.pack()
        
# Enter the tkinter main loop.
tkinter.mainloop()

In the above code we used a function named 'showinfo()', which is in the tkinter.messagebox module, to display the info dialog box. That is the reason we had an extra 'import' statement at the top of the code (you'll always need to import tkinter.messagebox if you want to use this function).

The syntax of the 'showinfo()' function is:

tkinter.messagebox.showinfo(title, message)


where title is a string that is displayed in the dialog box's title bar, and message is a string that is displayed in the main part of the dialog box.

  • Line 7 imports the 'tkinter' module, and line 6 imports the 'tkinter.messagebox' module.
  • Line 11 creates the root widget and assigns it to the variable 'root'.
  • Lines 14-17 contain the definition of the function 'do_something()' which is used for taking action when the button is clicked.
  • Lines 23-25 create the Button widget; note how the function is linked to the button by using the keyword 'command'; also the parentheses for the function are dropped.
  • On line 28 we make the button visible by using the usual 'pack()' method.
  • Finally, the last line calls the 'mainloop()' function.

GUI programs usually have a Quit button that closes the program when the user clicks it. In 'tkinter' this can be implemented very easily by creating a button (in the usual way, as explained above) that calls the root widget's destroy method as a callback function.

More specifically, in the newly created button you add the command

command=root.destroy


The code included below is a modified version of what we have immediately above, except for the new quit_button defined on lines 30-32.

In [50]:
#QuitProgram

# This program has a Quit button that calls
# the Tk class's destroy method when clicked.

import tkinter
import tkinter.messagebox

# Create the main window widget:
root = tkinter.Tk()

# Create the function for handling the click:
def do_something():
    tkinter.messagebox.showinfo('Response',
                                'Thanks for clicking the button.')


# Create a Button widget. The text 'Click Me!'
# should appear on the face of the Button. The
# do_something method should be executed when
# the user clicks the Button.
button1 = tkinter.Button(root,
                         text='Click Me!',
                         command=do_something)

# Create a Quit button. When this button is clicked
# the root widget's destroy method is called.
# (The main_window variable references the root widget,
# so the callback function is self.main_window.destroy.)
quit_button = tkinter.Button(root,
                             text='Quit',
                             command=root.destroy)


# Pack the Buttons.
button1.pack()
quit_button.pack()
        
# Enter the tkinter main loop.
tkinter.mainloop()

21.7 'Entry' widgets

An Entry widget is a rectangular area that the user can type input into. To retrieve the data that has been typed into the widget you must use the Entry widget's 'get()' method.

First, a simple example. We want a window with an Entry widget and a button. If we type a name in the Entry widget and then click the button, we want to get the message "Hello ..." displayed in the window, where the 'dots' will be replaced by the name that was entered. Here's a picture that illustrates what our widget will do:





Simple Entry widget with a button

The corresponding code appears below:

In [60]:
# EntryHello
#

from tkinter import *    # we won't have to prefix all of our 
                         # commands with 'tkinter'


root = Tk()

# Create an Entry widget and place it on the screen
entry = Entry(root, width=50, borderwidth=5)
entry.pack()

# Create a function that takes care of what happens
# when we click the button:
def myClick():
    hello = "Hello " + entry.get()
    myLabel = Label(root, text=hello)
    myLabel.pack()

# Create a click-able button and place it on the screen:
myButton = Button(root, text="Enter your name above", command=myClick)
myButton.pack()

# enter the main loop:
root.mainloop()

There are a few things that need to be pointed out. The 'get()' method used above returns a string; so, this output will have to be converted to the appropriate data type if the Entry widget is used for numeric input. Above, we concatenate the string "Hello" and whatever is being returned from the 'get()' method (see line 17); the result is stored in the variable 'hello', which is used as in the 'text' option of a Label widget (see line 18); this label is then displayed on the screen with the command on line 19. The rest of the code should is identical to what has already been discussed).

Next, we'll do something more useful. We create a program that allows the user to enter a distance in kilometers into an Entry widget, then click a button to see that distance converted in miles. The formula for converting kilometers to miles is:

Miles = Kilometers x 0.6214


We want our program to initially display the window shown below:



KiloConverter: the window initially displayed

The result is supposed to be displayed immediately under the Entry widget. We are going to use a Label widget in the program's main window to dynamically display the output. This simply amounts to creating an empty Label widget in the main window, and then writing code that displays the desired data in that label when a button is clicked.

The tkinter module provides a class named StringVar that can be used along with a Label widget to display data. This process is illustrated in the code included below:

In [1]:
# KiloConverterGUI
#
#
# This program converts distances in kilometers
# to miles. The result is displayed in a label
# on the main window.

from tkinter import *

# Create the main window:
root = Tk()


# We need a StringVar object to associate with
# an output label. Use the object's set method
# to store a string of blank characters:
value = StringVar()

# The convert method is a callback function for
# the Calculate button:
def convert():
    # Get the value entered by the user into
    # the kilo_entry widget:
    kilo = float(kilo_entry.get())

    # Convert kilometers to miles:
    miles = kilo * 0.6214

    # Convert miles to a string and store it
    # in the StringVar object. This will automatically
    # update the miles_label widget:
    value.set(miles)
    #return value
    

# Create three frames to group widgets:
top_frame = Frame()
mid_frame = Frame()
bottom_frame = Frame()

# Create the widgets for the top frame:
prompt_label = Label(top_frame, text='Enter a distance in kilometers:')
kilo_entry = Entry(top_frame, width=10)

# Pack the top frame's widgets:
prompt_label.pack(side='left')
kilo_entry.pack(side='left')

# Create the widgets for the middle frame:
descr_label = Label(mid_frame, text='Converted to miles:')
        
# Create a label and associate it with the StringVar object. 
# Any value stored in the StringVar object will automatically 
# be displayed in the label.
miles_label = Label(mid_frame, textvariable=value)

# Pack the middle frame's widgets:
descr_label.pack(side='left')
miles_label.pack(side='left')

# Create the button widgets for the bottom frame:
calc_button = Button(bottom_frame, text='Convert', command=convert)
quit_button = Button(bottom_frame, text='Quit', command=root.destroy)

# Pack the buttons:
calc_button.pack(side='left')
quit_button.pack(side='left')

# Pack the frames:
top_frame.pack()
mid_frame.pack()
bottom_frame.pack()

# Enter the tkinter main loop.
mainloop()

On lines 37-39 we create three frames: the 'top_frame' is for the label 'Enter distance in kilometers' and the Entry widget; the 'mid_frame' is for the label 'Converted to miles' and the empty label in which we display the output; finally, the 'bottom_frame' is for the two buttons, 'Convert' and 'Quit'. Inside these frames we position the widgets with the 'pack()' method that takes the argument side='left' (see lines 46-47, 58-59, 66-67).

On line 55 we use the argument

textvariable = variable,

which creates an association between the Label widget and the StringVar object that is referenced by the 'value' variable.

The buttons for the 'bottom_frame' are defined on lines 62-63, while on lines 66-67 they are placed on the screen. Recall that the frames must be "packed" separately, and the corresponding statements appear on lines 70-72. Finally, the code ends with a call to the 'mainloop()'.

In the last session we are going to explore a few more widgets.

HOMEWORK:

1). Re-write the 'QuitProgram' code using an OOP approach.

2). Write a program that can be used to calculate the average of three test scores. The GUI should have the following layout:



(The solutions to both questions are posted on Brightspace)

References:
T. Gaddis: Starting out with Python (4th Edition), Pearson Education Ltd., 2019