Previous: Widget binding
Up: Widgets
Next: Packing
Previous Page: Widget binding
Next Page: Packing

Command binding

WARNING - THIS SECTION NEEDS CHECKING - SOMETHING IS WRONG! Some widgets, such as button widgets, can have a command associated with them. This command is normally executed when button 1 is pressed, as in:

#Set up a button with a command"
    button .button1 -text "Press Here" -command "exec echo Hello there"
    pack .button1

Care must be taken when using variables within a command to execute, as follows:

#Set up a button with a command"
    button .button2 -text "Press Here" -command "exec echo Hello $Name"
    pack .button2

Here it is intended that pressing the button will cause a message involving the variable Name to be displayed. The problem with this is that the value of Name is the value when the widget is created, not the value when the button is pressed. This can be confusing at first, but the following example should demonstrate this:

set Name "Groucho Marx"
    #Set up a button with a command"
    button .button3 -text "Press Here" -command "exec echo Hello $Name"
    pack .button3

Set Name "Mickie Mouse"

When the button is pressed, Groucho Marx is displayed.

There are several solutions to this, but perhaps the simplest is to avoid using variables in the -command argument, and to call a procedure, which itself accesses global variables, as in the example which follows.

set Name "Groucho Marx"
    #Set up a button with a command"
    button .button3 -text "Press Here" -command "exec getName"
    pack .button3

Set Name "Mickie Mouse"

proc getName {} { global Name exec echo Hello $Name }

This time, when the button is pressed, Mickie Mouse is displayed.

WARNING - THIS SECTION NEEDS CHECKING - SOMETHING IS WRONG!

csstddm@brunel.ac.uk
Fri Aug 19 16:55:19 BST 1994