Every tkinter program consists of these things:
Windows, buttons, scrollbars, text areas, and other widgets—anything that you can see on the computer screen. (Generally, the term widget means any useful object; in programming, it is short for “window gadget.”)
Modules, functions, and classes that manage the data that is being shown in the GUI—you are familiar with these; they are the tools you’ve seen so far in this book.
An event manager that listens for events such as mouse clicks and keystrokes and reacts to these events by calling event handler functions.
Here is a small but complete tkinter program:
| import tkinter |
| window = tkinter.Tk() |
| window.mainloop() |
Tk is a class that represents the root window of a tkinter GUI. This root window’s mainloop method handles all the events for the GUI, so it’s important to create only one instance of Tk.
Here is the resulting GUI:
The root window is initially empty; you’ll see in the next section how to add widgets to it. If the window on the screen is closed, the window object is destroyed (though we can create a new root window by calling Tk() again). All of the applications we will create have only one root window, but additional windows can be created using the TopLevel widget.
The call on method mainloop doesn’t exit until the window is destroyed (which happens when you click the appropriate widget in the title bar of the window), so any code following that call won’t be executed until later:
| import tkinter |
| window = tkinter.Tk() |
| window.mainloop() |
| print('Anybody home?') |
When you try this code, you’ll see that the call on function print doesn’t get executed until after the window is destroyed. That means that if you want to make changes to the GUI after you have called mainloop, you need to do it in an event-handling function.
In Table 28, tkinter Widgets, there’s a list of some of the available tkinter widgets.
Widget |
Description |
---|---|
Button |
A clickable button |
Canvas |
An area used for drawing or displaying images |
Checkbutton |
A clickable box that can be selected or unselected |
Entry |
A single-line text field that the user can type in |
Frame |
A container for widgets |
Label |
A single-line display for text |
Listbox |
A drop-down list that the user can select from |
Menu |
A drop-down menu |
Message |
A multiline display for text |
Menubutton |
An item in a drop-down menu |
Text |
A multiline text field that the user can type in |
TopLevel |
An additional window |