ZetCode

Tk variables and traces

last modified November 24, 2026 Tcl 8.6

A Tk application has two kinds of state: the values stored in Tcl variables and the text or position shown by the widgets. Keeping those two in step by hand is tedious and easy to get wrong. Tk solves the problem with the -textvariable option and with Tcl variable traces, which let a widget and a variable share the same value.

This article shows how that binding works in both directions, how to read the current value back from a widget, how to react when a variable changes, and how to validate what a user types. All examples are complete scripts that can be run with wish.

Tk variables and set

Tk has no variable type of its own. A widget option such as -textvariable receives the name of an ordinary Tcl variable, and Tk attaches a trace to that variable. Changing the variable with set therefore changes the widget on the next display update. The first script creates a label bound to one variable and reads the result back with cget.

tkvar_intro.tcl
package require Tk

set message "Ready"
label .msg -textvariable message
pack .msg -padx 12 -pady 12

update
puts "variable: $message"
puts "label text: [.msg cget -text]"

set message "Working"
update
puts "after set: $message"

destroy .

The label is created with the variable name message, without a dollar sign; the option stores a name, not a value. update forces Tk to process pending display work, which is why the printed values are already current. The label keeps its own -text option in sync, so cget -text returns the same string as the variable.

$ wish tkvar_intro.tcl
variable: Ready
label text: Ready
after set: Working

The textvariable option

Several widgets can share one variable, and that is where the option pays off. An entry, a label and a status line can all display the same value without any copying code. The next script binds an entry and a preview label to city and changes the value in the model only.

textvariable.tcl
package require Tk

set city "Bratislava"

label .caption -text "City:"
entry .city -textvariable city -width 22
label .preview -textvariable city -relief sunken -anchor w

pack .caption -anchor w -padx 10 -pady 4
pack .city -padx 10
pack .preview -fill x -padx 10 -pady 8

update
puts "entry:   [.city get]"
puts "preview: [.preview cget -text]"

set city "Kosice"
update
puts "entry:   [.city get]"
puts "preview: [.preview cget -text]"

destroy .

Neither widget needed a command to update: set city wrote the variable, Tk noticed the write and refreshed both widgets. Note also that .city get returns the text currently held by the entry, while cget -text on the label returns the text the label displays. The variable remains the single source of truth.

$ wish textvariable.tcl
entry:   Bratislava
preview: Bratislava
entry:   Kosice
preview: Kosice

Reading and writing widget variables

The binding is not one-way. When a widget edits its content through its own command, Tk writes the new text back into the variable. In a real session that happens on every keystroke; in a script the same effect comes from the insert and delete subcommands of the entry.

widget_vars.tcl
package require Tk

set note ""
entry .note -textvariable note -width 30
pack .note -padx 10 -pady 10

.note insert end "first"
update
puts "after insert: '$note'"

.note insert end ", second"
update
puts "after insert again: '$note'"

.note delete 0 5
update
puts "after delete: '$note'"

set note "reset from the variable"
update
puts "entry get:      '[.note get]'"
puts "insert cursor:  [.note index insert]"
puts "chars in entry: [string length [.note get]]"

destroy .

The variable follows the widget commands immediately, without an explicit get. The reverse direction is just as direct: assigning note replaced the whole entry text, but the insertion cursor stayed where the earlier insert left it, at position 8. Text indices start at zero, so .note delete 0 5 removes the first five characters, including the comma.

$ wish widget_vars.tcl
after insert: 'first'
after insert again: 'first, second'
after delete: ', second'
entry get:      'reset from the variable'
insert cursor:  8
chars in entry: 23

Variable traces

A trace is a callback that Tcl runs whenever a variable is read, written or unset. Tk itself uses write traces to keep -textvariable bindings alive, and an application can add its own trace to the same variable. The callback receives three arguments: the variable name, an array index or empty string, and the operation.

variable_trace.tcl
package require Tk

set status "idle"

proc on_change {name1 name2 op} {
    global status
    puts "trace fired: $name1 is now '$status'"
}

trace add variable status write on_change

label .state -textvariable status
pack .state -padx 10 -pady 10

set status "loading"
update
set status "ready"
update

trace remove variable status write on_change
set status "closed"
puts "final value: $status"

destroy .

The trace fires for the two assignments, prints the new value, and is silent after trace remove. Inside the callback the variable already holds the new value, so $status is the new state; to compare with the old one, the callback has to remember it in another variable. The Tcl trace command page covers read and unset traces, array element traces and the trace info forms.

$ wish variable_trace.tcl
trace fired: status is now 'loading'
trace fired: status is now 'ready'
final value: closed

Validating entry input

A variable binding accepts any string, which is fine for a label but not for a field that must hold a number. Entry validation hooks into the widget before the change is committed. The -validate key option runs the callback for every edit, and %P in the command is replaced by the text the entry would contain. Returning 0 rejects the edit and leaves the old content in place.

validate_entry.tcl
package require Tk

proc digits_only {proposed} {
    if {$proposed eq "" || [string is integer -strict $proposed]} {
        return 1
    }
    puts "rejected: '$proposed'"
    return 0
}

entry .age -width 8 -validate key -validatecommand {digits_only %P}
pack .age -padx 10 -pady 10

.age insert end "42"
update
puts "accepted: '[.age get]'"

.age insert end "x"
update
puts "still:    '[.age get]'"

.age delete 0 1
update
puts "after deletion: '[.age get]'"

destroy .

The check allows an empty string, so the user can clear the field, and accepts any integer. Inserting x produces the candidate 42x, the callback returns 0, and the entry keeps 42. Other percent substitutions are %S for the inserted or deleted text, %v for the current validation mode and %W for the widget path. The Tcl string command page documents string is and its -strict switch.

$ wish validate_entry.tcl
accepted: '42'
rejected: '42x'
still:    '42'
after deletion: '2'

Model and view separation

The useful habit behind these bindings is to keep the data in variables and let widgets display it. Button commands then change only the variables, never the widget options. The next script implements a counter this way: the model is count, the view is a label bound to it, and the buttons call plain Tcl commands.

model_view.tcl
package require Tk

set count 0

label .caption -text "Clicks:"
label .value -textvariable count -width 4 -relief sunken
button .inc -text "+1" -command {incr count}
button .reset -text "Reset" -command {set count 0}

grid .caption -row 0 -column 0 -sticky w -padx 8 -pady 8
grid .value -row 0 -column 1 -padx 4
grid .inc -row 0 -column 2 -padx 4
grid .reset -row 1 -column 0 -columnspan 3 -sticky ew -padx 8 -pady 4

.inc invoke
.inc invoke
.inc invoke
update
puts "model count = $count"
puts "view text   = [.value cget -text]"

.reset invoke
update
puts "after reset = $count"
puts "view text   = [.value cget -text]"

destroy .

invoke runs a button's command exactly as a mouse click would, so the test needs no user. After three invocations the variable holds 3 and the label shows 3; the reset command returns both to 0. Because the command only touches the variable, the same counter would work with an entry or a progress bar instead of a label, without changing the logic.

$ wish model_view.tcl
model count = 3
view text   = 3
after reset = 0
view text   = 0

Linked widgets

Two input widgets can share one variable, which is how a slider and a text field stay in agreement. A scale writes its numeric value into -variable, an entry writes the typed text into -textvariable, and both read the same variable when it changes from outside.

linked_widgets.tcl
package require Tk

set level 40

scale .level -from 0 -to 2000 -orient horizontal -variable level -length 240
entry .show -textvariable level -width 6 -justify right
pack .level -padx 12 -pady 8
pack .show -pady 4

update
puts "scale: [.level get], entry: '[.show get]'"

set level 75
update
puts "after set: scale [.level get], entry: '[.show get]'"

.level set 200
update
puts "after scale set: level $level, entry: '[.show get]'"

.show insert end "0"
update
puts "after typing: level $level, scale [.level get]"

destroy .

The scale accepts numbers in its -from and -to range and writes the result back, which is why appending a zero to 200 produced 2000; a larger number would be clamped to the maximum. The entry accepted the same number as text. One caveat is worth knowing: clearing the entry would assign an empty string, and a scale cannot hold that, so Tk reports an error. Numeric fields that feed a scale should therefore be validated, as in the previous section.

$ wish linked_widgets.tcl
scale: 40, entry: '40'
after set: scale 75, entry: '75'
after scale set: level 200, entry: '200'
after typing: level 2000, scale 2000

A small form example

A form combines the pieces: one variable per field, entries bound to them, a status line bound to another variable, and a procedure that validates and saves the data. The layout uses grid, and the second column is given the extra space so the entries stretch with the window.

form_example.tcl
package require Tk

set name ""
set email ""
set status "Fill in the form"

proc submit {} {
    global name email status
    if {$name eq "" || $email eq ""} {
        set status "Both fields are required"
        return
    }
    if {[string first "@" $email] < 0} {
        set status "The e-mail address looks wrong"
        return
    }
    set status "Saved: $name <$email>"
}

label .name_l -text "Name"
label .mail_l -text "E-mail"
entry .name_e -textvariable name
entry .mail_e -textvariable email
button .save -text "Save" -command submit
label .status -textvariable status -anchor w -relief sunken

grid .name_l -row 0 -column 0 -sticky w -padx 8 -pady 4
grid .name_e -row 0 -column 1 -sticky ew -padx 8 -pady 4
grid .mail_l -row 1 -column 0 -sticky w -padx 8
grid .mail_e -row 1 -column 1 -sticky ew -padx 8
grid .save -row 2 -column 1 -sticky w -padx 8 -pady 8
grid .status -row 3 -column 0 -columnspan 2 -sticky ew -padx 8
grid columnconfigure . 1 -weight 1

.name_e insert end "Jane"
.mail_e insert end "jane.example.com"
.save invoke
update
puts "status: $status"

.mail_e delete 0 end
.mail_e insert end "jane@example.com"
.save invoke
update
puts "status: $status"
puts "name:   $name"
puts "e-mail: $email"

destroy .

submit reads the variables, not the widgets, so the same procedure could run from a menu item or a keyboard binding. The status label needed no update call of its own; assigning status refreshed it. The test fills the fields with insert, invokes the button twice and shows the rejected and accepted results. A real application would also clear the fields after saving, disable the button while the form is incomplete, and keep the data in a dictionary instead of separate global variables.

$ wish form_example.tcl
status: The e-mail address looks wrong
status: Saved: Jane <jane@example.com>
name:   Jane
e-mail: jane@example.com

Source

The standard options -textvariable and -variable are described in the options manual page, and the trace command in the Tcl manual. The widget pages document the entry, label, scale and button options used here.

This article explained how Tk widgets share Tcl variables through -textvariable, how to read values back, how traces react to changes, and how to validate and link input fields. Continue with Tk entry and text widgets, which covers multi-line text, tags, marks and undo, or read the Tcl variable command page for variables in namespaces.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.