Variables & reactivity
A variable holds a value and keeps it in sync with one or more widgets. Bind a variable to a widget and they update each other automatically — change the variable in code and every bound widget refreshes; edit a bound widget and the variable follows.
There are four kinds: StringVar, IntVar, DoubleVar, and BoolVar.
Two-way binding
Create a variable, then bind it to a widget through that widget's textVariable
(for text) or variable (for state) option. Several widgets can share one
variable:
const name = new StringVar('Guest');
app.TEntry({ textVariable: name }).pack.configure({ padx: 20, pady: 8 });
app.TLabel({ textVariable: name }).pack.configure();
Type in the entry and the label tracks it. Set it from code and both update:
name.value = 'Alice'; // entry and label both show "Alice"
console.log(name.value); // read the current value: "Alice"
Reacting to changes
Assign onChange to run code whenever the value changes — from the UI or from
code:
const volume = new IntVar();
volume.value = 50;
volume.onChange = () => console.log(`volume is now ${volume.value}`);
Checkboxes and radio buttons
Bind a BoolVar to a checkbutton with variable; .value reads and writes a
boolean:
const wrap = new BoolVar();
app.TCheckButton({ text: 'Word wrap', variable: wrap });
wrap.value = true; // checks the box
if (wrap.value) {
/* … */
}
Radio buttons share one variable and each carries a distinct value; the shared
variable holds whichever is selected:
const size = new StringVar('medium');
app.TRadioButton({ text: 'Small', variable: size, value: 'small' });
app.TRadioButton({ text: 'Medium', variable: size, value: 'medium' });
console.log(size.value); // 'medium'
Which variable type?
| Type | .value is |
Typical use |
|---|---|---|
StringVar |
string | entry / label text, comboboxes |
IntVar |
number (integer) | counters, integer settings |
DoubleVar |
number | scales, continuous values |
BoolVar |
boolean | checkbuttons |
Next
- Events & binding — reacting to UI events (vs. value changes)
- Widget basics
- Widget reference