Python GUI Programming (Tkinter and Python Programming)

Python GUI Programming (Tkinter and Python Programming)

This section will first introduce general GUI programming, and then focus on how to create Python GUI applications using Tkinter and its components.

Tkinter Module: Adding Tk to Your Application

So what do you need to do to make Tkinter a part of your application? First, an existing application is not necessary. If you wish, you can create a pure GUI program, but a program without interesting underlying functionality will not be useful. Getting the GUI program started and running requires the following five main steps.

  • 1. Import the Tkinter module (or use from Tkinter import *).
  • 2. Create a top-level window object to contain the entire GUI application.
  • 3. Build all GUI components (and their functionalities) on top of (or “within”) the top-level window object.
  • 4. Connect these GUI components through the underlying application code.
  • 5. Enter the main event loop. The first step is trivial: all GUI programs using Tkinter must import the Tkinter module. Gaining access to Tkinter is the primary step (see section 5.1.2).

Introduction to GUI Programming

Before giving examples, let’s briefly introduce GUI application development. This will provide you with some general background knowledge for your future learning. Creating a GUI application is like an artist painting. Traditionally, an artist works on a single canvas. The process works as follows: first, they start with a clean slate, which corresponds to the top-level window object used to build the remaining components. You can think of it as the foundation of a house or the easel of the artist. In other words, you must pour the concrete or set up the easel before assembling the real structure or canvas on top of it. In Tkinter, this foundation is called the top-level window object.

Windows and ControlsIn GUI programming, the top-level root window object contains all the small window objects that make up the GUI application. These may include text labels, buttons, list boxes, etc. These independent GUI components are called controls. So when we say to create a top-level window, it simply means that we need a place to arrange all the controls. In Python, this is generally written as follows:

top = Tkinter.Tk() # or just Tk() with "from Tkinter import *"

The object returned by Tkinter.Tk() is commonly referred to as the root window, which is also why some applications use root instead of top to refer to it. The top-level window is those parts that are displayed independently in the application. There can be multiple top-level windows in a GUI program, but only one can be the root window. You can choose to design all the controls first and then add functionality, or you can design the controls while adding functionality (which means steps 3 and 4 above will be mixed together). Controls can exist independently or as containers. If a control contains other controls, it can be considered the parent control of those controls. Conversely, if a control is contained by other controls, it is considered a child control of that control, and the parent control is the next container control that directly surrounds it. Typically, controls have some related behaviors, such as pressing a button or writing text in a text box. These user actions are called events, and the GUI’s response to such events is called a callback.

Event-Driven Processing

Event-driven GUI processing is inherently well-suited for client/server architecture. When starting a GUI application, some startup steps are needed to prepare the core parts for execution, just as a network server must first allocate sockets and bind them to a local address. A GUI application must first create all GUI components and then draw them on the screen. This is the responsibility of the layout manager (geometry manager), which will be detailed later. Once the layout manager arranges all controls (including the top-level window), the GUI application enters its server-like infinite loop. This loop will run continuously until a GUI event occurs, is processed, and then waits for more events to handle.

Layout ManagersTk has three types of layout managers to help position the control set. The most primitive one is called Placer. Its approach is very straightforward: you provide the size and placement of the controls, and the manager will place them accordingly. The problem is that you have to do this for all controls, which increases the burden on the programmer, as these operations should be done automatically.

The second layout manager is the one you will primarily use, called Packer. This name is very appropriate because it will pack the controls into the correct position (i.e., within the specified parent control), and then for each subsequent control, it will look for remaining space to fill. This process is similar to packing luggage into a suitcase while traveling.

The third layout manager is Grid. You can specify the placement of GUI controls based on grid coordinates using Grid. Grid will render each object in the GUI application at their grid positions. This chapter will use Packer.

Once Packer determines the size and alignment of all controls, it will place them properly on the screen. When all controls are placed, the application can enter the aforementioned infinite main loop. In Tkinter, the code is as follows:

Tkinter.mainloop()

This is generally the last segment of code that runs in the program. Once in the main loop, the GUI takes over the execution of the program from here. All other actions will be handled through callbacks, including exiting the application. When you select the File menu and click the Exit menu option, or directly close the window, a callback function will be called to terminate this GUI application.

Top-Level Window: Tkinter.Tk()

It was previously mentioned that all major controls are built on top of the top-level window object. This object is created in Tkinter using the Tk class and is instantiated as follows:

import Tkinter
>>> top = Tkinter.Tk()

In this window, you can place independent controls or piece together multiple components to form a GUI program. So what kinds of controls are there? Now let’s introduce these Tk controls.

Tk Controls

At the time of writing this book, there are a total of 18 types of Tk controls, as shown in Table 5-1. The latest controls include LabelFrame, PanedWindow, and Spinbox, which have been added since Python version 2.3 (via Tk 8.4).

Control Description
Button Similar to Label, but provides additional functionality such as mouse hover, press, release, and keyboard activity/events
Canvas Provides the ability to draw shapes (lines, ellipses, polygons, rectangles) and can contain images or bitmaps
Checkbutton A group of checkboxes, allowing any number to be checked (similar to HTML’s checkbox input)
Entry A single-line text box for collecting keyboard input (similar to HTML’s text input)
Frame A pure container that holds other controls
Label Used to contain text or images
LabelFrame A combination of label and frame, with additional label properties
Listbox Displays a list of options for the user to choose from
Menu A list of options that pops up when the Menubutton is pressed, allowing the user to select from it
Menubutton Used to contain menus (drop-down, cascading, etc.)
Message Message. Similar to Label, but can display multiple lines
PanedWindow A container control that can control the placement of other controls within it
Radiobutton A group of buttons, only one of which can be “pressed” (similar to HTML’s radio input)
Scale A linear “slider” control that gives the current set value based on a defined start and end value
Scrollbar Provides scrolling functionality for supported controls like Text, Canvas, Listbox, Entry, etc.
Spinbox A combination of Entry and Button, allowing for value adjustment
Text A multi-line text box for collecting (or displaying) user input text (similar to HTML’s textarea)
Toplevel Similar to Frame, but it provides a separate window container

We will not go into detail about Tk controls, as there are already many good documents available for you to refer to, such as the Tkinter theme page on the Python main site, or numerous printed resources and online resources about Tcl/Tk (see Appendix B). However, a few simple examples will be provided later to help you get started.

Leave a Comment