Main Content

The magic of -textvariable

Archive - Originally posted on "The Horse's Mouth" - 2006-02-08 08:39:18 - Graham Ellis

If you're writing a GUI based application, you'll need to hold pertinent information in variables in your program, AND display that pertinent information to the user.

The obvious way of doing this is to provide code that updates the display as required - in the case of Tcl/Tk you might write
   .wname configure -text "Melksham"
to change the text on the button called "wname" to Melksham, and
   set usersays [.wenter cget -text]
to read the text that the user's put into an entry box.

But there's a better alternative. Many widgets support the -textvariable option which allows the widget to be a reflection of the variable in your program all the time - in other words, if your program changes a variable then it will be automatically updated within the widget display, and if the user changes text within an entry box that's set up with this feature, then the variable within your program is automatically updated. Examples:
   entry .username -textvariable uname
   label .host -textvariable hostsystemname

Complete source code examples -
A Tcl/Tk form
In a Tcl/Tk popup message box
A Perl/Tk example