The Label widget is a standard Tkinter widget used to display a text or image on the screen. The label can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut.
When to use the Label Widget
Labels are used to display texts and images. The label widget uses double buffering, so you can update the contents at any time, without annoying flicker.
To display data that the user can manipulate in place, it’s probably easier to use the Canvas widget.
Patterns
To use a label, you just have to specify what to display in it (this can be text, a bitmap, or an image):
from Tkinter import * master = Tk() w = Label(master, text="Hello, world!") w.pack() mainloop()
If you don’t specify a size, the label is made just large enough to hold its contents. You can also use the height and width options to explicitly set the size. If you display text in the label, these options define the size of the label in text units. If you display bitmaps or images instead, they define the size in pixels (or other screen units). See the button description for an example how to specify the size in pixels also for text labels.
You can specify which color to use for the label with the foreground (or fg) and background (or bg) options. You can also choose which font to use in the label (the following example uses Tk 8.0 font descriptors). Use colors and fonts sparingly; unless you have a good reason to do otherwise, you should stick to the default values.
w = Label(master, text="Rouge", fg="red") w = Label(master, text="Helvetica", font=("Helvetica", 16))
Labels can display multiple lines of text. You can use newlines or use the wraplength option to make the label wrap text by itself. When wrapping text, you might wish to use the anchor and justify options to make things look exactly as you wish. An example:
w = Label(master, text=longtext, anchor=W, justify=LEFT)
You can associate a Tkinter variable with a label. When the contents of the variable changes, the label is automatically updated:
v = StringVar() Label(master, textvariable=v).pack() v.set("New Text!")
You can use the label to display PhotoImage and BitmapImage objects. When doing this, make sure you keep a reference to the image object, to prevent it from being garbage collected by Python’s memory allocator. You can use a global variable or an instance attribute, or easier, just add an attribute to the widget instance:
photo = PhotoImage(file="icon.gif") w = Label(parent, image=photo) w.photo = photo w.pack()