1.
14 Implementing a GUI with Tkinter 23
90
91 # This code iterates through the commands to do the drawing and
92 # demonstrates the use of the __iter(self)__ method in the
93 # PyList class above.
94 for cmd in graphicsCommands:
95 cmd.draw(t)
96
97 file.close()
98 t.ht()
99 screen.exitonclick()
100 print("Program Execution Completed.")
101
102 if __name__ == "__main__":
103 main()
Listing 1.19 A Graphics Program
1.14 Implementing a GUI with Tkinter
The word GUI means Graphical User Interface. Implementing a Graphical User
Interface in Python is very easy using a module called Tkinter. The Tcl/Tk language
and toolkit was designed as a cross-platform method of creating GUI interfaces.
Python provides an interface to this toolkit via the Tkinter module.
A GUI is an event-driven program. This means that you write your code to respond
to events that occur in the program. The events occur as a result of mouse clicks,
dragging the mouse, button presses, and menu items being selected.
To build a GUI you place widgets in a window. Widgets are any element of a GUI
like labels, buttons, entry boxes, and sometimes invisible widgets called frames. A
frame is a widget that can hold other widgets. The drawing application you see in
Fig. 1.6 is one such GUI built with Tkinter. In this section we’ll develop this drawing
application so you learn how to create your own GUI applications using Tkinter and
to improve or refresh your Python programming skills.
To construct a GUI you need to create a window. It is really very simple to do this
using Tkinter.
root = tkinter.Tk()
This creates an empty window on the screen, but of course does not put anything
in it. We need to place widgets in it so it looks like the window in Fig. 1.6 (without
the nice picture that Denise drew for us; thanks Denise!). We also need to create
event handlers to handle events in the drawing application.
Putting widgets in a window is called layout. Laying out a window relies on a
layout manager of some sort. Windowing toolkits support some kind of layout. In
Tkinter you either pack, grid, or place widgets within a window. When you pack
widgets it’s like packing a suitcase and each widget is stacked either beside or below
the previous widget packed in the GUI. Packing widgets will give you the desired
layout in most situations, but at times a grid may be useful for laying out a window.