Python Series Part 17: Understanding Tkinter Labels

Jarret B

Well-Known Member
Staff member
Joined
May 22, 2017
Messages
454
Reaction score
519
Credits
19,511
We’ve already been using labels in the examples for the previous Python articles dealing with Tkinter window methods, but we never got too deep into using them.

Labels are one of the basic objects used for Graphical User Interface (GUI) windows. They are used to just place text or a picture in a window.

There are quite a few options for the Label widget. Some we have seen, very few, so there is quite a bit about ‘Labels’ to learn.

NOTE: In the examples I will use, I am using the ‘grid’ method. All the options used work for any of the three methods (grid, place, and pack). For simple line commands used as code, I will not include the ‘.grid’ portion.

Text

This is an option for the label that specifies what text will be displayed by the label.

If we wanted a label on the screen that contains ‘This is an example.’, the line of code would be:

Code:
l1 = Label(text="This is an example.").grid(row=0,column=0)

You can use any valid string for the text, just place it in the double quotes.

Textvariable

It is possible to use the value in a string variable to be placed into the label. In this way, you can change the variable’s value and this will update the text in the label.

The first thing is to create the variable and then give it a value. The variable is then used to create the label:

Code:
text1 = StringVar()
text1.set("Label Value")
l1 = Label(textvariable=text1)
l1.grid(row=1,column=1)

In the first line, we initialize the variable ‘text1’. In the second line, we set the variable ‘text1’ to the value of ‘Label Value’.

In the third line, we set up the label ‘l1’ with the ‘textvariable=text1’. The fourth line places the label in the window.

Later, if we need, we can set ‘text1’ to another value when something occurs, such as a button click, so the label text changes.

Foreground

The text in a label is in the foreground. We can change the color of the foreground so the text is not the default ‘black’ color.

There are two methods for setting a color:
  1. Name - ‘fg=‘color’’
  2. Hex Value = #000000
The name is simply the name of the color, such as:
  • black
  • white
  • red
  • green
  • blue
  • purple
  • green
  • yellow
  • orange
  • and others….
For example, let’s say we want a label that has purple text and says ‘Example Label’.

Code:
l1 = Label(text="Example Label",fg='purple')

You can set the color with more precision using the hex values. The hex values are three sets of two digits. The first to digits represent a value of the ‘red’ where ‘00’ has no red and ‘FF’ contains the most red. So, to get bright red text, the hex value would be ‘#FF0000’.

The second set of two digits controls the amount of green. The third set of digits controls the blue.

The order is RGB (Red-Green-Blue).

Setting all three sets to ‘0’ will generate ‘black’ and setting all to ‘F’ will make the color white.

Purple would be ‘#FF00FF’ and is:

Code:
l1 = Label(text="Example Label",fg='#FF00FF')

Background

We can set the foreground color, the text, but what if you want to set the background color, the part behind the text?

The background parameter is the same as the foreground parameter, just ‘bg’ and not ‘fg’.

In the example, we make a label that has a foreground of ‘purple’ and a background of ‘blue’:

Code:
l1 = Label(text="Example Label",fg='purple',bg='blue')

The same can be done with hex value:

Code:
l1 = Label(text="Example Label",fg='#FF00FF',bg='#0000FF')

Font

Seeing as how we can change the colors, why not the font as well? You need to make sure that any font you use exists on the system where the python code is being executed.

On my system, I am running Ubuntu, so I have a font named ‘ubuntu’.

In the example, the label will have the text ‘Example Label’ be purple and the font will be ‘ubuntu’:

Code:
l1 = Label(text="Example Label",fg='purple',font='ubuntu')

You can also specify a size for the font with the parameter ‘font=(‘font_name’,#)’ where ‘#’ is the size. An example is:

Code:
l1 = Label(text="Example Label",fg='purple',font=('ubuntu',18)

You can change the font and size for every label, or object.

You can also add the following a comma and enclosed in quotes:
  • underline
  • bold
  • italic
If you use multiple options, then you need to separate each by a comma and in quotes.

Justify

If you have a label with multiple lines, you can justify the text as:
  • Left
  • Center
  • Right
Keep in mind that we can center the text within the label. The text must comprise multiple lines.

An example of three labels that are each justified differently:

Code:
from tkinter import *
root = Tk()
root.title('Label Justify')
root.geometry("400x500")

for row in range(0,7):
    root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
    root.grid_columnconfigure(col, weight=1)

l1 = Label(text="Left\nJustified",bg='blue',width=25,justify='left')
l2 = Label(text="Center\nJustified",bg='blue',width=25,justify='center')
l3 = Label(text="Right\nJustified",bg='blue',width=25,justify='right')
l1.grid(row=1,column=1)
l2.grid(row=2,column=1)
l3.grid(row=3,column=1)

root.mainloop()

Figure 1 shows the output.

Figure 1.JPG

FIGURE 1

Here you can see that the top label has been justified to the left side of the central position. The ‘L’ is above the ‘J’ to the left. And the second label has both lines centered. The third label centers with the words lined up on the right side.

Notice that the ‘\n’ is a new line to create multiple lines.

Anchor (Height and Width)

We’ve covered anchors before, so I won’t get too detailed. Here you can specify a position for the text within the object. The object needs to be large enough to show the placement. In the next example, I’ll use a label width of ‘25’ characters and a height of ‘3’ characters. Remember that the ‘height’ and ‘width’ of the object are in characters.

The anchor specifies the compass position as well as ‘center’. Figure 2 shows the output of the example:

Code:
from tkinter import *
root = Tk()
root.title('Label Justify')
root.geometry("400x800")

for row in range(0,9):
    root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
    root.grid_columnconfigure(col, weight=1)

l1 = Label(text="NW",bg='blue',width=25,height=3,anchor=NW)
l2 = Label(text="N",bg='blue',width=25,height=3,anchor=N)
l3 = Label(text="NE",bg='blue',width=25,height=3,anchor=NE)
l4 = Label(text="W",bg='blue',width=25,height=3,anchor=W)
l5 = Label(text="Center",bg='blue',width=25,height=3,anchor=CENTER)
l6 = Label(text="E",bg='blue',width=25,height=3,anchor=E)
l7 = Label(text="SW",bg='blue',width=25,height=3,anchor=SW)
l8 = Label(text="S",bg='blue',width=25,height=3,anchor=S)
l9 = Label(text="SE",bg='blue',width=25,height=3,anchor=SE)
l1.grid(row=0,column=1)
l2.grid(row=1,column=1)
l3.grid(row=2,column=1)
l4.grid(row=3,column=1)
l5.grid(row=4,column=1)
l6.grid(row=5,column=1)
l7.grid(row=6,column=1)
l8.grid(row=7,column=1)
l9.grid(row=8,column=1)

root.mainloop()

Figure 2.JPG

FIGURE 2

You can use the ‘anchor’ parameter with ‘justify’ parameter to not only justify text, but place it in a specific spot within the object.

BorderWidth and Relief

The borderwidth is the number of pixels for a border around the label. You can use the parameter ‘borderwidth’ or ‘bd’.

By default, unless you specify a ‘relief’, the label is ‘flat’ and the border is not seen, so a ‘borderwidth’ is not visible.

The ‘relief’ is a style of border used for the label and the types are:
  • flat
  • groove
  • raised
  • ridge
  • solid
  • sunken
The relief styles are in Figure 3.

Figure 3.JPG

FIGURE 3

By adjusting the borderwidth, you can make them look different.

NOTE: The options for ‘Label’ aren’t done. Keep in mind that these options can be a mix from one option to all of them.

Style

This is an interesting option. Here, we can create a ‘theme’ for all specific objects. For example, I can set font, font size, text color, background color, etc for all specific objects, such as labels. I can also create custom styles for specific objects, such as a header label.

There seems to be a problem, though. The ‘style’ option is not under ‘tk’, but under ‘ttk’.

When you import all of ‘tk’ with the line ‘from tkinter import *’, this imports all of ‘tk’, but that does not include ‘ttk’. TTK is ‘Theme Tkinter’.

Most of the parameters, such as ‘fg’ don’t exist in ‘ttk’. In ‘ttk’ the parameter is ‘foreground’.

Let me give a quick example:

Code:
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Label Test')
root.geometry("400x500")

for row in range(0,7):
    root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
    root.grid_columnconfigure(col, weight=1)
l1 = ttk.Label(text="Example Label")
l2 = ttk.Label(text="Example Label")
l1.grid(row=1,column=1)
l2.grid(row=2,column=1)

root.style = ttk.Style(root)
root.style.configure('TLabel', font=('Ubuntu', 25), foreground='blue', background='white')

root.mainloop()

Here, I set the ‘style’ for root as ‘root.style’. I then configure the ‘root.style’ with the command ‘root.style.configure’ for all labels (TLabel). I then specify all settings I want to configure for all the labels.

Basically, for any object, just use the object name with ‘T’ at the beginning. Another example is ‘TButton’ for all buttons in the window.

Also note that any label to use ‘style’ must be preceded by ‘ttk’ such as in ‘ttk.Label’.

Now, for custom buttons.

In the next example, which the output is shown in Figure 4, the header label has a special theme:

Code:
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Label Test')
root.geometry("400x500")

for row in range(0,7):
    root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
    root.grid_columnconfigure(col, weight=1)

l0 = ttk.Label(text="Header\nLabel",style="Header.TLabel")
l1 = ttk.Label(text="Example Label")
l2 = ttk.Label(text="Example Label")
l0.grid(row=0,column=0,columnspan=4,sticky='ew')
l1.grid(row=2,column=1)
l2.grid(row=3,column=1)

root.style = ttk.Style(root)
root.style.configure('TLabel', font=('Ubuntu', 15), foreground='blue', background='white')
root.style.configure('Header.TLabel', font=('Alex Brush', 20),foreground='red',justify=CENTER,anchor=EW)

root.mainloop()

Figure 4.JPG

FIGURE 4

Here, we setup a special theme called ‘Header.TLabel’. We assign it to ‘l0’ with the parameter ‘style=Header.TLabel’. Keep in mind that this only works if the label is a ‘ttk.Label’. If the ‘ttk.Label’ has no style listed, it will use the default.

Do note that the ‘Header’ is using a different font that I installed on my system. I also centered the text on two lines, using ‘justify’, and anchored it to cover the complete cell. The reason that the ‘cell’ covered the whole row, is that I used ‘columnspan’ to make the entire row one cell.

This may be a section that you should practice with, especially as we learn more widgets.

Underline

In most applications, there is a menu of sorts, where it underlines a letter of each word on the menu. This is a ‘shortcut’ to open the menu. In this parameter, we can specify a letter to be underlined.

Most times, this is not usually used with labels, but with a menu.

WrapLength

Wraplength is a measurement in pixels about how many characters can be on a line. Once the number of pixels has been met, the text is wrapped to the next line, so the Label width remains the same. If you do not wrap the text, the label can be widened to hold all the text (default), or the text is cut off and not visible.

An example of a wraplength of 200 pixels is:

Code:
l1 = Label(wraplength=100, text="This is a long string for wrapping.")

The output of the label is shown in Figure 5.

Figure 5.JPG

FIGURE 5

Padding


We can add padding to the sides of a label around the text. The padding is inside the label border.

There are two options:

  1. padx - add padding to the left and right of the text
  2. pady - add padding to the top and bottom if the text
The value given to the options is in pixels.

An example is the following code:

Code:
l1 = Label(text="Normal;",bg='blue')
l2 = Label(text="PadX",bg='blue',padx=15)
l3 = Label(text="PadY",bg='blue',pady=15)
l4 = Label(text="PadXY",bg='blue',padx=15,pady=15)

The output is shown in Figure 6.

Figure 6.JPG

FIGURE 6

TakeFocus


Once we get into more widgets, the need for ‘takefocus’ will be more apparent.

Basically, as we have multiple objects in the window, we can use the TAB key to change the focus from on widget to another. Usually, there is no need for a label to have focus. By default, labels cannot get focus.

Just add the option:

Code:
takefocus=YES

This will allow the label to take focus. The only problem is that the label focus is not apparent by default. With another widget, such as the button, there is an extra line around the button’s box. The extra box does not occur for the label, by default. To see how to change this, look at the section below called ‘HighlightBackground, HighlightColor and HighlightThickness’.

To turn off the focus:

Code:
takefocus=NO

ActiveForeground and ActiveBackground (Status)

For some widgets, including Labels, there is a ‘status’ option. The ‘status’ option has three values:
  1. normal - the default
  2. active - let’s you set a different forground’background color
  3. disabled - still shows the label, but it is grayed out
If the ‘status’ is ‘active’, then you can cause an appearance change. Usually this may be when something occurs such as a button press.

The code for ‘activeforeground’ and ‘activebackground’ just goes in the parenthesis with the other options:

Code:
activeforground=‘red’
activebackground=‘blue’

DisabledForeground

When you disable a label’s state, the color of the foreground defaults to a gray color, but this is system specific. The ‘disabledforeground’ option lets you specify the color you want when the label is disabled.

The code option could be:

Code:
disabledforeground=’red’

HighlightBackground, HighlightColor and HighlightThickness

When a label has focus, the highlight is ‘black’, but when the widget loses focus, you can set the ‘highlightbackground’ color

To set the color of the highlight, when a widget has focus, it is set by ‘highlightcolor’.

The ‘highlightthickness’ is the number of pixels that the highlight box is around the label. By default, this number is ‘0’, or it does not exist. Therefore ‘takefocus’ is not apparent. If you set ‘highlightthickness=1’ or higher, then you can see it.

A good example is:

Code:
from tkinter import *
root = Tk()
root.title('Label Focus and Highlight')
root.geometry("400x800")

for row in range(0,9):
    root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
    root.grid_columnconfigure(col, weight=1)

l1 = Label(text="L1",takefocus=YES,highlightthickness=2,highlightbackground='yellow')
l2 = Label(text="L2",takefocus=YES,highlightthickness=2,highlightbackground='yellow')
l3 = Label(text="L3",takefocus=YES,highlightthickness=2,highlightbackground='yellow')
l4 = Label(text="L4",takefocus=YES,highlightthickness=2,highlightbackground='yellow')
l1.grid(row=1,column=1)
l2.grid(row=2,column=1)
l3.grid(row=3,column=1)
l4.grid(row=4,column=1)

root.mainloop()

The output is shown in Figure 7.

Figure 7.JPG

FIGURE 7

Cursor


When the cursor moves over a label, you can change the cursor from the default. The cursors are:
  • arrow
  • X_cursor
  • arrow
  • based_arrow_down
  • based_arrow_up
  • boat
  • bogosity
  • bottom_left_corner
  • bottom_right_corner
  • bottom_side
  • bottom_tee
  • box_spiral
  • center_ptr
  • circle
  • clock
  • coffee_mug
  • cross
  • cross_reverse
  • crosshair
  • diamond_cross
  • dot
  • dotbox
  • double_arrow
  • draft_large
  • draft_small
  • draped_box
  • exchange
  • fleur
  • gobbler
  • gumby
  • hand1
  • hand2
  • heart
  • icon
  • iron_cross
  • left_ptr
  • left_side
  • left_tee
  • leftbutton
  • ll_angle
  • lr_angle
  • man
  • middlebutton
  • mouse
  • pencil
  • pirate
  • plus
  • question_arrow
  • right_ptr
  • right_side
  • right_tee
  • rightbutton
  • rtl_logo
  • sailboat
  • sb_down_arrow
  • sb_h_double_arrow
  • sb_left_arrow
  • sb_right_arrow
  • sb_up_arrow
  • sb_v_double_arrow
  • shuttle
  • sizing
  • spider
  • spraycan
  • star
  • target
  • tcross
  • top_left_arrow
  • top_left_corner
  • top_right_corner
  • top_side
  • top_tee
  • trek
  • ul_angle
  • umbrella
  • ur_angle
  • watch
  • xterm
Setting the option allows the cursor to change over the label and turn back to the default when the cursor leaves the label.

An example of a label is:

Code:
l1 = Label(text="L1",cursor="trek")

Here, the cursor changes to the Star Trek Enterprise when the cursor is moves over the ‘l1’ label.

Image

It is possible to place an image in a Label instead of text.

There are two methods to cover:
  1. BitmapImage - monochrome images
  2. PhotoImage - color images usually as PNG
The coding is as follows:

Code:
loaded_image = PhotoImage(file="/home/jarret/Python/tux1.png")
l1 = Label(image=loaded_image)
l1.grid(column=1, row=1)

It may be best practice to always use ‘PhotoImage’ instead of ‘BitmapImage’.

In the first line, we load the image into the variable ‘loaded_image’. You can change this variable to any valid name you wish to use. In the second line, we load the image into the label with the ‘image’ option and pass the image variable we used in line one. In line three, we place the label on the window.

Compound

If you want to use both text and an image in a label, you need to specify the option ‘compound’. The different choices for ‘compound’ are:
  • TOP
  • BOTOM
  • LEFT
  • RIGHT
  • CENTER
If you do not specify ‘compound’ then the text will not be displayed since it defaults to ‘NONE’. Otherwise, the image will be placed to the side specified by compound. So, if you specify ‘TOP’, the image is above the text.

Sample code is as follows and the output is in Figure 8:

Code:
from tkinter import *
root = Tk()
root.title('Label Image')
root.geometry("400x800")

for row in range(0,9):
    root.grid_rowconfigure(row, weight=1)
for col in range(0,3):
    root.grid_columnconfigure(col, weight=1)

loaded_image = PhotoImage(file="/home/jarret/Python/tux1.png")
l1 = Label(image=loaded_image, text="Top", compound=TOP)
l2 = Label(image=loaded_image, text="Left", compound=LEFT)
l3 = Label(image=loaded_image, text="Center", compound=CENTER)
l4 = Label(image=loaded_image, text="Right", compound=RIGHT)
l5 = Label(image=loaded_image, text="Bottom", compound=BOTTOM)
l1.grid(column=1, row=0)
l2.grid(column=1, row=2)
l3.grid(column=1, row=4)
l4.grid(column=1, row=6)
l5.grid(column=1, row=8)

root.mainloop()

Figure 8.JPG

FIGURE 8

Conclusion


I know this was long, but I tried to get all the different options for Label covered with examples, especially when there are few or none available for some options.

I’m hoping this will make for a good reference for the Label widget. If you are planning on programming with TKinter, be aware that these options will be repeated on other widgets. A lot of the options definitely exist on multiple widgets, if not all of them.
 


Follow Linux.org

Members online


Top