Common Tk Errors

The following problems are frequently reported by users writing Tcl/Tk programs and are easy to correct with a little guidance. This section is not meant to be a complete guide to writing Tcl/Tk, but serves to address a few common situations.

Global Scope for -variable and -textvariable

Many Tk widgets allow you to tie a widget to a Tcl variable so that changes to either the widget or variable are mirrored in the other. This handy feature makes widget data instantly available in Tcl code, without the need to access the widget command:

label .tot_rev-text 0-textvariable totalRevenue
set totalRevenue 263124 ;# updates widget also

The most common problem when using -variable and -textvariable options is forgetting that the variables the options name are referenced as global variables. If you create widgets inside of a procedure and then access the widget’s variable, be sure to define the variable as global.

proc mk_totRev {} {
    label .tot_rev -text 0 -textvariable totalRevenue
    pack .tot_rev
    global totalRevenue
    set totalRevenue 23128
}

The -command String Must Be a Tcl List

Tk widgets (particularly buttons) often let you specify code to be run when the widget is selected. This code is known as a callback. You should put the code in braces, not quotes, to prevent variables from being interpreted until the user selects the widget. This is illustrated in the following example:

set count 0
button .b -text "Increment" -command {puts $count; incr count}
pack .b

Callback scripts can ...

Get Tcl/Tk in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.