back

The Variable Classes (BooleanVar, DoubleVar, IntVar, StringVar)

If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.

There’s no way to track changes to Python variables, but tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.

When to use the Variable Classes

Variables can be used with most entry widgets to track changes to the entered value. The Checkbutton and Radiobutton widgets require variables to work properly.

Variables can also be used to validate the contents of an entry widget, and to change the text in label widgets.

Patterns #

To create a tkinter variable, call the corresponding constructor:

var = StringVar()

Note that the constructor takes an optional widget argument, but no value argument; to set the value, call the set method:

var = StringVar()
var.set("hello")

The constructor argument is only relevant if you’re running tkinter with multiple Tk instances (which you shouldn’t do, unless you really know what you’re doing).

You can use the trace method to attach “observer” callbacks to the variable. The callback is called whenever the contents change:

def callback(*args):
    print "variable changed!"

var = StringVar()
var.trace("w", callback)
var.set("hello")

FIXME: add Entry/Label/OptionMenu patterns

Methods

get/set

get() => value

set(string)

The get method returns the current value of the variable, as a Python object. For BooleanVar variables, the returned value is 0 for false, and 1 for true. For DoubleVar variables, the returned value is a Python float. For IntVar, it’s an integer. For StringVar, it’s either an ASCII string or a Unicode string, depending on the contents.

The set method updates the variable, and notifies all variable observers. You can either pass in a value of the right type, or a string.

trace

trace(mode, callback) => string

trace_variable(mode, callback)

Add a variable observer. Returns the internal name of the observer (you can use this to unregister the observer; see below).

The mode argument is one of “r” (call observer when variable is read by someone), “w” (call when variable is written by someone), or “u” (undefine; call when the variable is deleted).

FIXME: describe the mode argument and how the callback should look, and when it is called.

trace_vdelete

trace_vdelete(mode, observer name)

Remove an observer. The observer name is the string returned by trace_variable, when the observer was first registered.

trace_vinfo

trace_vinfo() =>list

FIXME: add description

 

A Django site. rendered by a django application. hosted by webfaction.