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 Gui.py 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 from Swampy:
from swampy.Gui import *
Or, depending on how you installed Swampy, like this:
from Gui import *
Then instantiate a Gui object:
g = Gui()g.title('Gui')g.mainloop()
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:
Button: A widget, containing text or an image, that performs an action when pressed.
Canvas: A region that can display lines, rectangles, circles and other shapes.
Entry: A region where users can type text.
Scrollbar: A widget that controls the visible part of another widget.
Frame: A container, often invisible, that contains other widgets.
The empty gray square you see when you create a Gui is a Frame. When you create a new widget, it is added to this Frame.