Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 40 ยท Widgets Basics

Tkinter Variables: StringVar, IntVar and trace

Learn Tkinter control variables: StringVar, IntVar, DoubleVar and BooleanVar, how textvariable links widgets, how trace reacts to changes, and common pitfalls.

Widgets need a way to share values with your program. Reading and writing a widget directly works (entry.get()), but it ties your code to one widget. Tkinter's control variables are a better channel: a small object that holds a value, and that widgets can be linked to. Change the variable and every linked widget updates; type in the widget and the variable changes. They also let you react to changes with trace.

The four variable classes

Class Holds Default Read with
tk.StringVar text "" get() returns str
tk.IntVar whole number 0 get() returns int
tk.DoubleVar float 0.0 get() returns float
tk.BooleanVar True or False False get() returns bool

Each has set(value) and get(). A variable needs a root window to exist, so create the Tk() first (or pass master=).

Python
import tkinter as tk

root = tk.Tk()
name = tk.StringVar(value="Ada")
age = tk.IntVar(value=36)
subscribed = tk.BooleanVar()

print(name.get(), age.get(), subscribed.get())   # Ada 36 False
name.set("Grace")

Linking a variable to a widget

Give the widget the variable instead of a value:

Python
import tkinter as tk

root = tk.Tk()
name = tk.StringVar()

tk.Entry(root, textvariable=name).pack(padx=20, pady=(20, 6))
tk.Label(root, textvariable=name, font=("Segoe UI", 14)).pack(pady=(0, 20))
root.mainloop()

Type in the entry and the label below changes with every keystroke, with no callback and no polling: both widgets read the same variable. This is the main reason to use variables, and the pattern scales: a status bar, a title and a preview can all show one value.

Which widget options accept a variable?

  • Label, Button, Entry, Message: textvariable
  • Checkbutton: variable (with onvalue/offvalue)
  • Radiobutton: variable (with value)
  • Scale, Spinbox, Scrollbar-like inputs: variable or textvariable
  • OptionMenu and ttk.Combobox: variable / textvariable

A model of how it works

A control variable is an observable value. The stand-in below rebuilds the idea in plain Python: a value, a list of observers (widgets), and trace_add. It is the same design, so after this the real thing is no longer magic.

Python Stand-in: an observable variable

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.

Reacting to changes with trace

var.trace_add(mode, callback) runs callback whenever the variable is read ("read"), written ("write") or deleted ("unset"). The callback receives three strings, the internal variable name, an index and the mode, which most code ignores.

Python
def on_change(*args):
    text = search.get()
    status.config(text=f"{len(text)} characters")

search = tk.StringVar()
search.trace_add("write", on_change)
tk.Entry(root, textvariable=search).pack()
status = tk.Label(root, text="0 characters")
status.pack()

This is the idiom for live search boxes, character counters, enabling a button only when a form is valid and updating a total as fields change. Older code uses trace("w", callback), which is deprecated; use trace_add. To remove a trace, keep the id it returns and call var.trace_remove("write", trace_id).

Here is a validation example in the same style. The stand-in shows the rules; wiring them to a real trace_add callback is just button.config(state=...).

Python Stand-in: enable Submit only when valid

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.

Gotchas

1. The variable must be kept alive. If it is a local variable in a function that returns, Python garbage-collects it and the widget stops updating (the same reason PhotoImage needs a reference). Store it on self.

Python
def build(parent):
    var = tk.StringVar(value="hi")        # lost when build() returns!
    tk.Label(parent, textvariable=var).pack()

Fix: self.var = tk.StringVar(...), or attach it to the widget.

2. IntVar.get() raises TclError on bad text. If an entry linked to an IntVar contains "abc" or is empty, get() fails:

Python
count = tk.IntVar()
tk.Entry(root, textvariable=count).pack()
try:
    n = count.get()
except tk.TclError:
    n = 0                                  # empty or not a number

For free-form numeric input, use a StringVar and convert it yourself with validation.

3. Two Tk() roots, two worlds. A variable belongs to one interpreter. Creating a variable before Tk() raises an error ("Too early to create variable"), and variables are shared only within the same root.

4. BooleanVar values. set() accepts True/False, 1/0 or the strings "yes", "no", "true". get() always returns bool.

5. Default shared variables. Two widgets that should be independent must not share a variable, or they will change together. This is useful for radio groups (Checkbuttons and Radiobuttons) and a bug elsewhere.

Variables vs. reading the widget

Approach Good for
entry.get() One-off reads in a button callback
StringVar linked to widget Live updates, sharing between widgets, traces, resetting forms
Plain attribute on self Application state that no widget displays

A tidy form class often keeps one variable per field in a dictionary, which makes it easy to read or clear all fields at once:

Python
fields = {key: tk.StringVar() for key in ("name", "email", "city")}
values = {key: var.get() for key, var in fields.items()}
for var in fields.values():
    var.set("")                      # clear the form

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which option links a Label's text to a StringVar?

    Labels, buttons and entries use textvariable. Checkbuttons and radiobuttons use variable.
  2. 2. A StringVar created inside a function stops updating its Label after the function returns. Why?

    Store the variable on self (or a long-lived object) so Python does not free it.
  3. 3. What happens if IntVar.get() is called while its linked Entry contains 'abc'?

    IntVar tries to convert the text to an int. Catch TclError or use a StringVar plus your own validation.
  4. 4. Which call runs a function every time a StringVar changes?

    trace_add with mode 'write' registers a callback for writes. The older trace('w', ...) form is deprecated.

Summary

  • StringVar, IntVar, DoubleVar and BooleanVar hold values with get() and set().
  • Link them with textvariable= or variable= so widgets update each other automatically.
  • trace_add("write", callback) reacts to changes: live search, validation, running totals.
  • Keep references to variables, and expect TclError from get() on bad numeric text.
  • Use variables for shared, live values; plain attributes for hidden application state.

Next: The Entry Widget