13 Chapter 13: Graphical User Interfaces using Tkinter

GRAPHICAL USER INTERFACES

USING TKINTER

A blue background with 0s and 1s, three tables with blue screens, and a hand holding a phone.

 

Topics Covered:

  • Graphical user interface
  • Event handlers
  • Accessing the date and time

 

Graphical User Interfaces

All of the programs we looked at so far used a text-based user interface (TUI). In this chapter, we learn how to develop grapical user interface (GUI) programs. In Python, a GUI program features a window full of widgets.

widget is a visual component such as a label, button, entry, or image that you can place on the window. To create a GUI program, we will need to import tkinter (pronounced “t”, “k”, “inter”), which is a Python module that defines these GUI widgets.

Each widget is an object that has properties and responds to events, such as a key press or a mouse click. The widget properties can be assigned initial values when the program starts up. These properties can also be modified while the program is running.

To code a GUI program using TK, you typically follow these four steps:

Table with the steps to code a GUI Program using TK

Suppose you wanted to build the GUI window shown below. The window consists of three widgets. We will describe each of these widgets, as well as how we can add the cool title at the top of the window.

GUI window titled "This is a cool title", a button with "Hit this button!" and a label with "Cool Label".

After importing the tkinter widgets and creating a Tk object named window, we use the title() method to place a caption at the top of the window. Next, we create three widgets and place each of them on the screen.

button is a rectangle that is usually associated with an event-handler function that gets triggered when the user clicks on the button. To create the button, we use the Button() constructor, or function, to initialize the button text, background color, and width. When calling this constructor, you need to assign it to a variable; in this case, we stored it as myButton.

To place a widget on the screen, you use the grid() method and provide arguments of the window object, as well as several optional arguments. In this instance, we padded 100 pixels to the left and right of the button and padded 20 pixels above and below the button.

label widget simply places text on the window. Arguments to the Label() constructor include the window object and the text to display. In our example, we set the optional arguments to change the background and foreground colors of the label. We used the grid() method to add the label to the screen using a 20 pixel border on all four sides of the label.

An entry widget is a rectangle that allows the user to input text using the keyboard. The Entry() constructor requires the window object as a parameter. In our example, we set the width of the entry to 20 characters.

The mainloop() method will “listen” for user events like keys pressed and mouse clicks, but we haven’t defined any event handlers yet. We will show that next. You can click on the button, but nothing will happen.

Code for TK Import

 

Event Handlers

As mentioned, you can change a property of a widget during program execution. This is done by referencing the widget variable with the property to change enclosed in square brackets [ ]. We illustrate this process by creating an event handler that will toggle the background color of the button between yellow and purple.

To create an event handler, you must first define a function that will determine which code executes when the event is triggered, and then add the name of that function to the widget’s constructor. In our example, we defined a function named toggleBgColor() and added the command property when creating the button. Notice how the parentheses are not included at the end of command=toggleBgColor in this instruction.

Code to change label from "Cool Label" to "Hooray".

In addition to demonstrating the button event handler, we included two other examples of how you can dynamically modify a widget property. We changed the foreground color of the button to white and modified the text of the label to “Hooray”. When running this modified version of the program and clicking on the button one time, the window looks like this:

GUI window with the "Cool Label" highlight changed to say "Hooray".

Problem: The Marketing Department at a local hardware store has asked you to develop a program for it. The managers are always asking about the percentage markup and the profit margin for various items in the inventory.

The program will require two inputs, the selling price and the purchase price of an item. The markup can be computed by subtracting the purchase price from the selling price. Other formulas needed are:

Formula: percentage markup = markup/purchase price and profit margin = markup/selling price.

 

where these quotients are expressed as percentages. The user interface should look like this:

GUI asking for imputs for the formula from the previous image.

The solution to this problem is shown below. To retrieve data from the entries, we needed to create string variables and associate them with the entries. We used “readonly” entries to place the three outputs using the set() method of the string variables.

Python code to compute markup, percentage markup, and profit margin.

You will notice in this example that the placement of the widgets using the grid() method was done by using rows and columns. The top row is row 0 and the leftmost column is column 0. You can imagine the process as placing the widgets into a table or spreadsheet. You can also allow a widget to span across multiple columns as illustrated by the “Compute Stuff!” button in this program

Below is a sample run of the program with the store purchasing an item for $38.50 and selling it for $47.99. Notice how the three entry widgets that were defined to be readonly are “grayed out” on the screen. This indicates that the keyboard user isn’t able to enter values into those fields, although the program is allowed to modify the text shown in the fields by using the set() method.

GUI with the imputs for Selling Price ($47.99) and Purchase Price ($38.50) to equal Markup ($9.49), Percentage Markup (24.6%) and Profit Margin (19.8%).

 

Accessing Date and Time

In applications that are being used to log logging activities, it is useful to access the current date or time. Python has a module called datetime that provides this capability. This module is quite versatile and provides numerous ways to format the current date and/or time. In the example below, we call the today() method and then print the current date in a MM-DD-YYYY format. We then use that same thisDate variable to print the current time in a HH:MM:SS XM format. A great explanation with more examples can be viewed here:

https://www.w3schools.com/python/python_datetime.asp

Code to import date and time.

Listbox Widget

The listbox widget is used to display a list of items from which a user can select any number of items. In the example below, we first create a list colorList, associate a string variable colorString with it, and then call the Listbox()  constructor. We use the set() method to assign a value to colorString. The function colorChange() retrieves the selected item and we use that index to change color of the window background.

Code to configure a ListBox Widget

Sample program run:

Listbox widget with red, blue, yellow, orange, and white.

 

Radiobutton Widget

The radiobutton is a widget that is used to allow a user to select one out of a group of choices. On the next page, we present a program that serves as the cashier for the local bowling alley. It uses an entry for the games bowled and three radio buttons to choose the bowler type, one of child, adult, or senior. The cashier() function is called on a button click. It uses the get() method to determine the bowler type and the number of games. The label’s config() method is used to change the label text based on the total cost. Notice how three radiobutton widgets all use the same integer variable bowlerType to ensure only one of them can be selected at any given time.

Code to configure a Radiobutton Widget.

Sample program run:

Radiobutton Widget asking for number of games (3), an adult ticket ($3.50), and a button to compute the total ($10.50).

 

Chapter Review Exercises:

13.1. What is a widget? Describe three common widgets.

 

 

Programming Projects:

13.1. Use the Python module tkinter to create the following graphical user interface. Do not worry about functionality at this point. You will add that in later. Be sure to modify your program so that it generates a match (title, colors, spacing, etc.) to this window:

A widget for ordering from "Mark's Family Restaurant".
  • The default choices should be selected. That is, a burger with fries and a Coke.
  • To allow for multiple list boxes to be selected, add the attribute for each one: exportselection=0
  • Change the restaurant name to your own name. Notice the font size and bold face changes.
  • Notice the Entry widget at the bottom is read only.
  • Use the same colors as those shown above.

13.2. Add a function to your Project 13.1 program and connect it to the “Add to the order” button. When the user clicks this button, the function should add the prices of the selected entrees, sides, and drinks to the total and display that total (using a dollar sign and 2 decimal places) using the entry widget at the bottom of the screen.

13.3 Make the following changes to Project 13.2:

  • Include a label and an entry widget that gets the customer’s name
  • When the user clicks the “Add to the order” button, print to the Interactive window a detailed receipt with labels (restaurant name, receipt message, current date, current time, customer name, entrée, side, drink, total)
  • When the user clicks the “Add to the order” button, write the following data to a comma-delimited text file named “restaurantData.csv”: current date, current time, customer name, entrée, side, drink, total

License

Icon for the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License

Python Textbook Copyright © 2022 by Dr. Mark Terwilliger is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book