Widgets – the building blocks of GUI apps
Now that we have our top level or the root window ready, it is time to think over a question—which components should appear in the window? In Tkinter jargon, these components are called widgets.
In the following example, we will add two widgets, a label, and a button to the root frame. Note how all the widgets are added between the skeleton code that we defined in the first example:
from tkinter import *
root = Tk()
label = Label(root, text="I am a label widget")
button = Button(root, text="I am a button")
label.pack()
button.pack()
root.mainloop()
The following is a description of the preceding code:
• This code added a new instance named label for the Label widget. The first parameter defined root as its parent or container. The second parameter configured its text option as I am a label widget.
• Similarly, we defined an instance of a Button widget. This is also bound to the root window as its parent.
• We used the pack() method, which is essentially required to position the label and button widgets within the window. We will discuss the pack() method and several other related concepts when exploring the geometry management task. However, you must note that some sort of geometry specification is essential for the widgets to be displayed within the top-level window.
There are two ways to create widgets in Tkinter.
The first way involves creating a widget in one line and then adding the pack() method (or other geometry managers) in the next line, as follows:
my_label = Label(root, text="I am a label widget")
my_label.pack()
Alternatively, you can write both the lines together, as follows:
Label(root, text="I am a label widget").pack()
You can either save a reference to the widget created (my_label, as in the first example), or create a widget without keeping any reference to it (as demonstrated in the second example).
You should ideally keep a reference to the widget in case the widget has to be accessed later on in the program. For instance, this is useful in case you need to call one of its internal methods or for its content modification. If the widget state is supposed to remain static after its creation, you need not keep a reference to the widget.
Getting to know the core Tkinter widgets
Now, you will get to know all the core Tkinter widgets. You have already seen two of them in the previous example—the Label and Button widgets. Now, let’s see all the other core Tkinter widgets.
Toplevel | Label | Button |
Canvas | Checkbutton | Entry |
Frame | LabelFrame | Listbox |
Menu | Menubutton | Message |
OptionMenu | PanedWindow | Radiobutton |
Scale | Scrollbar | Spinbox |
Text | Bitmap Class | Image Class |
Let’s write a program to display all of these widgets in the root window.