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 |
|
Default value |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
- 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 untypedVariableshare 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.
Note
IntVar.get()andDoubleVar.get()raisetkinter.TclErrorwhen 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
callbackwhenever the variable is written, read, or unset — the way to react to a bound widget changing without a per-widgetcommand.- 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:
- 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:
LocaleVar#
- class LocaleVar(master=None, src='', name=None)
ttkbootstrap’s
StringVarsubclass whose value re-translates itself when the application locale changes (it listens for the<<LocaleChanged>>event).srcis the source string to translate. Use it for label text that should follow the active locale — see Localization.
See also#
Variables guide — binding variables to widgets, traces, and the numeric-coercion gotcha.
Validation — checking what the user types.
tkinter Variable classes — the upstream reference.