GUI elements are called widgets (short for "window gadgets"). Probably the simplest widget is the Label widget, which is uneditable text or icons (or both). A label widget labels part of a GUI. It's often used to label other widgets. Unlike most other widgets, labels aren't interactive. A user can't click on a label (alright, a user can, but the label won't do anything). Still, labels are important and you'll probably use at least one every time you create a GUI.
The Labeler program creates a root window and adds a label to it. The label widget simply declares that it is a label. Figure 10.7 illustrates the program.
Figure 10.7: A label can provide information about a GUI.
First, I set up the Labeler program by importing Tkinter and creating a root window:
# Labeler # Demonstrates a label # Michael Dawson - 6/5/03 from Tkinter import * # create the root window root = Tk() root.title("Labeler") root.geometry("200x50")
A Frame is a widget that can hold other widgets (such as Label widgets). A frame is like the cork in a corkboard; you use it as a base on which to place other things. So, I create a new frame:
# create a frame in the window to hold other widgets app = Frame(root)
Any time you create a new widget, you must pass its master (the thing that will contain the widget) to the constructor of the new object. Here, I pass root to the Frame constructor. As a result, the new frame is placed inside the root window.
Next, I invoke the grid() method of the new object:
app.grid()
grid() is a method that all widgets have. It's associated with a layout manager, which lets you arrange widgets. To keep things simple, I save the discussion of layout managers for a bit later in this chapter.
I create a Label widget by instantiating an object of the Label class:
# create a label in the frame lbl = Label(app, text = "I'm a label!")
By passing app to the Label object's constructor, I make the frame that app refers to the master of the Label widget. As a result, the label is placed in the frame.
Widgets have options that you can set. Many of these options affect how the widget appears. By passing the string "I'm a label!" to the text parameter, I set the widget's text option to that string. As a result, the text I'm a label! appears when the label is displayed.
Next, I invoke the object's grid() method:
lbl.grid()
This ensures that the label will be visible.
Last, but not least, I invoke the root window's event loop to start up the GUI:
# kick off the window's event loop root.mainloop()