The Button Widget

The Button Widget

The Tk button widget is useful for letting the user activate a command of the application. It comes in three basic forms:

Command buttons have a text or image label and execute a command in the application.
Check buttons are useful for allowing the user to choose options.
Radio buttons are used to select from a set of mutually exclusive options.

Associating a command with a button is very simple:

button .hello -command {puts "hello"}

The above makes a button named .hello that when clicked, executes the command puts "hello" which prints a greeting.

It's important to remember that button commands are executed at the global scope. This means that they do not have access to variables at the scope at which the button was defined. If you create a button inside a procedure, you might be surprised to find that when executed, its associated command no longer has access to any of the variables defined in that procedure.

Also, you should be aware that all variables which are used in a command will obtain their current value, not the value they had when the command was defined. For example,

set x 34
button .xvalue -command {puts $x}
set x 43

unless someone changed the value of x again, when this button is clicked, it will print 43. You can pass the value of a variable at the time the command is defined, by constructing a list and substituting the value in, so:

set x 34
button .xvalue -command [list puts $x]
set x 43

This button will always print 34 irrespective of the current value of x.

With that out of the way, let's examine some cool things you can do with the three different kinds of buttons.