Variables#

A variable is a typed value holder that binds to a widget: set the variable and the widget updates; edit the widget and the variable updates. Pass one as textvariable= (an Entry, Label, or Combobox), as variable= (a Checkbutton, Radiobutton, or Scale), and read it back with .get(). The Variables guide shows them in use; this page is the API spec.

The variable classes#

Each class wraps a value of one Python type and coerces get() to it. The base Variable is untyped; the four typed subclasses differ only in the type get() returns and their default value. All share one constructor and the same methods.

Class

get() type

Default value

Variable

str

""

StringVar

str

""

IntVar

int

0

DoubleVar

float

0.0

BooleanVar

bool

False

class StringVar(master=None, value=None, name=None)

A variable holding a str — the usual choice for an Entry or Label. IntVar, DoubleVar, BooleanVar, and the untyped Variable share this constructor and every method below.

Parameters:
  • master – the root or a widget; inferred from the default root if omitted.

  • value – the initial value (the class default if omitted).

  • name – the underlying Tcl variable name; auto-generated if omitted.

Reading and writing#

get()

Return the current value, coerced to the class’s type.

Return type:

str | int | float | bool

Note

IntVar.get() and DoubleVar.get() raise tkinter.TclError when the bound widget’s text isn’t a valid number — an empty or half-typed Entry, for instance. Catch it or validate the field (see the Error handling recipe and Validation).

set(value)

Set the value; every widget bound to the variable updates immediately.

Parameters:

value – the new value.

Returns:

None.

Reacting to changes#

trace_add(mode, callback)

Run callback whenever the variable is written, read, or unset — the way to react to a bound widget changing without a per-widget command.

Parameters:
  • mode"write", "read", or "unset" (or a list of them).

  • callback – called as callback(name, index, op); the arguments are rarely needed — read the variable with .get() inside.

Returns:

a trace id, for trace_remove().

Return type:

str

trace_remove(mode, cbname)

Remove a trace added with trace_add().

Parameters:
  • mode – the mode the trace was added with.

  • cbname – the trace id returned by trace_add.

Returns:

None.

trace_info()

List the traces currently on the variable.

Returns:

a list of (mode_list, cbname) pairs.

Return type:

list

LocaleVar#

class LocaleVar(master=None, src='', name=None)

ttkbootstrap’s StringVar subclass whose value re-translates itself when the application locale changes (it listens for the <<LocaleChanged>> event). src is the source string to translate. Use it for label text that should follow the active locale — see Localization.

See also#