Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 40 ยท Styling with ttk

ttk Themed Widgets: Button, Entry, Combobox, Progressbar

Move from classic tk widgets to modern ttk: Label, Button, Entry, Checkbutton, Combobox, Spinbox, Scale and Progressbar, with variables, states and validation.

Tkinter has two widget sets. The classic widgets (tk.Button, tk.Label, ...) are drawn by Tk itself with options like bg and fg. The themed widgets in tkinter.ttk are drawn by a theme engine and look like native controls on Windows, macOS and Linux. They also add widgets that the classic set lacks: Combobox, Notebook, Treeview, Progressbar, Separator and more.

For new programs, use ttk wherever a ttk version exists. This lesson shows the common ttk widgets, how they differ from the classic ones (styling is done through styles instead of options), and how to read and validate their values. The widget code is read-only; runnable blocks model the data logic.

Importing

Python
import tkinter as tk
from tkinter import ttk

Importing ttk after tkinter is the convention. Watch for a trap: from tkinter import * followed by from tkinter.ttk import * makes ttk widgets silently replace the classic ones with the same names (Button, Label, Entry...), and options like bg= then fail with TclError: unknown option "-bg". Always use ttk.Button, never star imports.

A small form

Python
root = tk.Tk()
root.title("Order")

frame = ttk.Frame(root, padding=16)
frame.grid(sticky="nsew")

name = tk.StringVar()
size = tk.StringVar(value="Medium")
qty = tk.IntVar(value=1)
gift = tk.BooleanVar()

ttk.Label(frame, text="Name").grid(row=0, column=0, sticky="w", pady=4)
ttk.Entry(frame, textvariable=name, width=24).grid(row=0, column=1, pady=4)

ttk.Label(frame, text="Size").grid(row=1, column=0, sticky="w", pady=4)
ttk.Combobox(frame, textvariable=size, values=["Small", "Medium", "Large"],
             state="readonly", width=21).grid(row=1, column=1, pady=4)

ttk.Label(frame, text="Quantity").grid(row=2, column=0, sticky="w", pady=4)
ttk.Spinbox(frame, from_=1, to=20, textvariable=qty, width=6).grid(row=2, column=1, sticky="w", pady=4)

ttk.Checkbutton(frame, text="Gift wrap", variable=gift).grid(row=3, column=0, columnspan=2, sticky="w")
ttk.Button(frame, text="Place order", command=place_order).grid(row=4, column=0, columnspan=2, pady=(12, 0))

root.mainloop()

A tidy window shows labeled controls in two columns: a text entry, a drop-down with three sizes that cannot be typed into, a number box with arrows, a check box and a button, all in the platform's native look. Every input is tied to a Tkinter variable (StringVar, IntVar, BooleanVar, DoubleVar), so reading a value is qty.get() and changing it from code is qty.set(3). Layout managers such as grid are covered in the Layout Managers chapter.

The ttk widget family

Widget Purpose Key options
ttk.Label text or image text, image, anchor, wraplength, justify
ttk.Button clickable text, command, state, default
ttk.Entry one-line text textvariable, show="*", validate, validatecommand, width
ttk.Checkbutton on/off variable, onvalue, offvalue
ttk.Radiobutton one of many variable, value
ttk.Combobox drop-down list values, state="readonly", <<ComboboxSelected>>
ttk.Spinbox number stepper from_, to, increment, values, wrap
ttk.Scale slider from_, to, orient, command, variable
ttk.Progressbar progress mode, maximum, value, length
ttk.Separator, ttk.Sizegrip line, resize handle orient

Because ttk widgets take their looks from the theme, many classic options (bg, fg, font, relief) are not accepted. You style them with ttk.Style (Styles and Themes). The options that remain are behavioral: state, width, textvariable, command, padding, cursor, takefocus.

States

ttk uses a flag system instead of a single state string. widget.state(["disabled"]) sets a flag, widget.state(["!disabled"]) clears it, and widget.instate(["disabled"]) tests it. The state="disabled" option also works. Flags include disabled, readonly, focus, active, pressed, selected and invalid. Themes style each flag combination (for example a grayed-out disabled button).

Combobox in detail

A combobox is an entry plus a list. With state="readonly" the user can only pick from the list; without it they may type anything. Respond to a choice with the virtual event:

Python
box = ttk.Combobox(frame, textvariable=size, values=sizes, state="readonly")
box.bind("<<ComboboxSelected>>", lambda e: update_price())
box.current(1)             # select the item at index 1

box.get() returns the current text, box.current() the index (-1 if the text is not in the list) and box["values"] = new_list replaces the choices at run time. A pointer to remember: <<ComboboxSelected>> fires on a pick from the list, not while typing.

Spinbox and Scale

Spinbox shows a number with small arrows; values can also come from a list (values=("low", "mid", "high")). It accepts any typed text, so you must validate on read. Scale returns a float like 42.0 even for integer ranges, which is why code often does round(scale.get()). The command callback of a Scale receives the new value as a string.

Progressbar

Python
bar = ttk.Progressbar(frame, orient="horizontal", length=240, mode="determinate", maximum=100)
bar.pack()
bar["value"] = 40          # 40 percent
bar.step(10)               # add 10, wraps at maximum

In determinate mode the bar shows a known fraction: set value from 0 up to maximum. In indeterminate mode it shows a moving block for work of unknown length: bar.start(10) begins animating (every 10 ms) and bar.stop() ends it. Combine with after (Canvas Animation with after()) or with a background worker (Threads and Background Work), never with a blocking loop.

Entry validation

An Entry can reject keystrokes before they appear. Register a function with root.register and pass the substitution codes you need:

Python
def only_digits(proposed):
    return proposed == "" or proposed.isdigit()

vcmd = (root.register(only_digits), "%P")           # %P = text after the change
entry = ttk.Entry(frame, validate="key", validatecommand=vcmd)

The entry now ignores letters: typing a does nothing. The validation function returns True to accept the change and False to reject it. %P is the value the entry would have, %S the text being inserted, %d the action (1 insert, 0 delete). Use validate="focusout" for rules like "must be a valid e-mail" that cannot be checked per keystroke, and mark the field as invalid with entry.state(["invalid"]).

Variables and traces

Tkinter variables can notify you when they change, which lets one widget drive another:

Python
def on_change(*args):
    total.set(price[size.get()] * qty.get())

size.trace_add("write", on_change)
qty.trace_add("write", on_change)

Whenever the combobox or spinbox changes its variable, the total updates. The stand-in below is not Tkinter; it models a variable with trace callbacks, a validate function and the Scale string-versus-float detail.

Python Stand-in: variables with traces, validation and Scale values

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.

Progress arithmetic

When you report progress, convert "done out of total" to the bar's value and a label. This logic is independent of the widget:

Python Stand-in: progress and step arithmetic

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.

Common mistakes

  • Using from tkinter.ttk import * after from tkinter import *; ttk classes shadow the classic ones.
  • Passing bg=, fg= or font= to a ttk widget. Configure a style instead.
  • Forgetting state="readonly" on a Combobox when only list values are valid.
  • Creating a variable inside a function and not keeping it, so it is garbage collected and the widget shows an empty value.
  • Treating Spinbox text as a number without catching ValueError.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does ttk.Button(root, bg='red') raise an error?

    Themed widgets are drawn by the theme engine; change their looks with ttk.Style.
  2. 2. How do you make a Combobox that accepts only values from its list?

    A readonly Combobox lets the user pick but not type.
  3. 3. What does ttk.Scale.get() return for an integer range?

    Scale always works with floats, so round() the value if you need an integer.
  4. 4. Which Progressbar mode shows a moving block for work of unknown length?

    Use mode='indeterminate' with start() and stop().

Summary

  • tkinter.ttk provides native-looking widgets and extras: Combobox, Spinbox, Progressbar, Notebook, Treeview.
  • Import it as from tkinter import ttk and avoid star imports.
  • Tie inputs to Tkinter variables; use trace_add to react to changes.
  • Style ttk widgets through styles, set state with flags (state(["disabled"])).
  • Validate entries with validate and validatecommand.

Next: ttk Styles and Themes