Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 40 ยท Widgets Basics

Tkinter Labels, Fonts and Colors

Use Tkinter Label and Message widgets, choose fonts with tuples or the font module, set colors by name or hex, add images and update text while the program runs.

A Label displays text or an image. It is the simplest widget and the best place to learn the options that nearly every widget shares: colors, fonts, padding, borders and alignment. This lesson also covers Message (a label that wraps its text), reading and changing options at runtime, and how Tk measures things.

Creating a Label

Python
import tkinter as tk

root = tk.Tk()
tk.Label(root, text="Hello, Tkinter").pack()
root.mainloop()

The signature pattern is Widget(parent, **options). You can also set options after creation:

Python
label = tk.Label(root, text="Initial")
label.pack()
label.config(text="Changed")        # same as label.configure(...)
label["text"] = "Changed again"     # dictionary style
print(label.cget("text"))           # read an option

The options you will use most

Option Meaning Example
text The string to show (use \n for line breaks) text="Total:"
font Font tuple or Font object ("Arial", 14, "bold")
fg / bg Text and background color fg="white", bg="#264653"
width, height Size in characters and lines for text labels width=20
padx, pady Extra space inside the border padx=10
anchor Where text sits when the label is bigger than it needs anchor="w"
justify Alignment of the lines of multi-line text justify="left"
wraplength Wrap text at this many pixels wraplength=240
relief, bd Border style (flat, raised, sunken, groove, ridge, solid) and thickness relief="solid", bd=1
image, compound Show an image; compound combines it with text compound="left"
textvariable Bind the text to a StringVar (next lessons) textvariable=name_var
cursor Mouse pointer shape cursor="hand2"
Python
import tkinter as tk

root = tk.Tk()
root.title("Labels")

tk.Label(root, text="Plain label").pack(pady=4)
tk.Label(root, text="Styled", fg="white", bg="#2a9d8f",
         font=("Helvetica", 16, "bold"), padx=20, pady=8).pack(pady=4)
tk.Label(root, text="A long sentence that should wrap onto several lines.",
         wraplength=180, justify="left", relief="groove", padx=8, pady=8).pack(pady=4)
root.mainloop()

Two things confuse beginners. First, width and height of a text label count characters of the font's "0" glyph, but for an image label they are pixels. Second, anchor only has a visible effect when the label is larger than its text, usually because you gave width or the label is stretched by the layout.

Fonts

A font is normally a tuple: (family, size) or (family, size, style words). Positive sizes are points; negative sizes are pixels.

Python
("Arial", 12)
("Courier New", 10, "bold")
("Segoe UI", 14, "bold italic underline")
("Helvetica", -20)           # 20 pixels tall

Font names differ by system. Segoe UI exists on Windows, SF Pro or Helvetica Neue on macOS, and DejaVu Sans on many Linux systems. Tk silently falls back to a default when a family is missing, so portable programs often use the named fonts instead:

Python
import tkinter as tk
import tkinter.font as tkfont

root = tk.Tk()
print(tkfont.names())                 # TkDefaultFont, TkTextFont, TkFixedFont, ...
print(tkfont.families()[:5])          # installed family names

default = tkfont.nametofont("TkDefaultFont")
default.configure(size=12)            # changes EVERY widget using the default

big = tkfont.Font(family="Georgia", size=28, weight="bold")
tk.Label(root, text="Big title", font=big).pack()
big.configure(slant="italic")         # all widgets using `big` update live
root.mainloop()

A Font object is shared, so changing it once restyles every widget that uses it. That makes it perfect for "zoom text" features and consistent headings. font.measure("some text") returns the pixel width of a string, and font.metrics("linespace") gives line height.

Because Tk measures fonts in points but displays in pixels, the same text looks different at different screen densities. This stand-in shows the conversion used by Tk, where the scaling factor is dpi / 72.

Python Stand-in: points to pixels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Colors

Colors are strings, in one of two forms.

  • Named colors: "red", "navy", "lightgray", "SystemButtonFace" (a Windows system color). Tk knows about 750 names.
  • Hex: "#rgb", "#rrggbb" or "#rrrrggggbbbb", such as "#2a9d8f".

To work with the components, convert in plain Python. A common need is checking text contrast. The stand-in below implements hex parsing and a readable-text rule, and you can paste pick_text_color straight into a real program to choose black or white text for any background.

Python Stand-in: hex colors and readable text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a window you can also ask Tk to convert a name to numbers: root.winfo_rgb("navy") returns 16-bit values (0, 0, 32768), so divide by 256 to get the usual 0-255 range.

Updating a label while the program runs

Labels are display-only, so the usual pattern is to keep the label as an attribute and call config:

Python
import tkinter as tk
import time

root = tk.Tk()
clock = tk.Label(root, font=("Consolas", 32), fg="#264653")
clock.pack(padx=30, pady=20)

def tick():
    clock.config(text=time.strftime("%H:%M:%S"))
    root.after(1000, tick)

tick()
root.mainloop()

A second option is a StringVar linked with textvariable, which updates the label automatically when the variable changes; Tkinter Variables explains it.

Images in labels

Python
photo = tk.PhotoImage(file="logo.png")     # PNG and GIF are supported
label = tk.Label(root, image=photo, text="Logo", compound="top")
label.image = photo                         # keep a reference!
label.pack()

The last line matters. Tk does not keep your PhotoImage alive: if the Python variable goes out of scope (for example inside a function), the image is garbage-collected and the label goes blank. Storing it on the widget or on self prevents that. For JPEG and other formats, use the Pillow library's ImageTk.PhotoImage.

Message: a wrapping label

tk.Message is a text widget that automatically wraps at a given width (in pixels) and keeps an aspect ratio. Most modern code simply uses Label(wraplength=...), which gives you more control, so reach for Message only when you want its automatic sizing.

Python
tk.Message(root, text="This text wraps without any manual line breaks.",
           width=200, bg="#f1faee").pack(padx=10, pady=10)

Clickable labels

A label can respond to clicks with a binding (chapter 4), which makes link-style text:

Python
link = tk.Label(root, text="Open website", fg="blue", cursor="hand2",
                font=("Segoe UI", 11, "underline"))
link.pack()
link.bind("<Button-1>", lambda event: print("clicked"))

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which font tuple gives bold 14-point Arial?

    The tuple order is family, size, then style words.
  2. 2. A label shows an image, but the picture disappears. What is the most likely cause?

    Tk does not hold the Python PhotoImage alive. Keep a reference, for example label.image = photo.
  3. 3. How do you change a label's text after it is created?

    Options are changed with config()/configure() or the label['text'] = ... item syntax.
  4. 4. What does a negative font size mean?

    Positive sizes are points; negative sizes are device pixels.
  5. 5. Which option wraps long label text at a pixel width?

    wraplength breaks the text into lines no wider than that many pixels.

Summary

  • Label(parent, text=..., font=..., fg=..., bg=...) shows text or images; change it later with config.
  • Fonts are tuples (family, size, styles) or shareable Font objects; named fonts keep a program consistent.
  • Colors are names or #rrggbb strings; compute contrast yourself in Python when needed.
  • Keep a reference to every PhotoImage, or the picture vanishes.
  • wraplength, justify, anchor and padx/pady control layout inside the label; Message wraps by itself.

Next: Buttons and Commands