Chapter 19. Case Study: Tkinter


Most of the programs we have seen so far are text-based, but many programs use graphical user interfaces, also known as GUIs.

Python provides several choices for writing GUI-based programs, including wxPython, Tkinter, and Qt. Each has pros and cons, which is why Python has not converged on a standard.

The one I will present in this chapter is Tkinter because I think it is the easiest to get started with. Most of the concepts in this chapter apply to the other GUI modules, too.

There are several books and web pages about Tkinter. One of the best online resources is An Introduction to Tkinter by Fredrik Lundh.

I have written a module called that comes with Swampy. It provides a simplified interface to the functions and classes in Tkinter. The examples in this chapter are based on this module.

Here is a simple example that creates and displays a Gui:

To create a GUI, you have to import Gui and instantiate a Gui object:

from Gui import *

g = Gui()

When you run this code, a window should appear with an empty gray square and the title Gui. mainloop runs the event loop, which waits for the user to do something and responds accordingly. It is an infinite loop; it runs until the user closes the window, or presses Control-C, or does something that causes the program to quit.

This Gui doesn’t do much because it doesn’t have any widgets. Widgets are the elements that make up a GUI; they include:


A widget, containing text or ...

Get Think Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.