Book HomeMastering Perl/TkSearch this book

4.8. Radiobutton Values

Groups of Radiobuttons are designed to all use the same -variable option but with unique -value options for each individual Radiobutton. When you select a Radiobutton, any other Radiobuttons assigned the same -variable will be unselected, and that variable will be assigned the -value associated with the selected Button.

You must always use -value when creating Radiobuttons. If you don't, they won't select/deselect correctly. There are no defaults for -value.

Here is an example that uses Radiobuttons to control the background color:

# setup the default value we would like
$rb_value = "red";
$mw->configure(-background => $rb_value);

# create the Radiobuttons that will let us change it
foreach (qw(red yellow green blue grey)) {
  $mw->Radiobutton(-text => $_,
                   -value => $_,
                   -variable => \$rb_value,
                   -command => \&set_bg)->pack(-side => 'left');
}

# function to change the background color using $rb_value
sub set_bg {
  print "Background value is now: $rb_value\n";
  $mw->configure(-background => $rb_value);
}

We are storing the status of our Radiobutton group in $rb_value. We set it to an initial value of "red", which happens to match the first Radiobutton we are creating. When any of the Radiobuttons are clicked, including the one currently selected, the subroutine set_bg will be called. This subroutine will print the new value of $rb_value and then change the background of our MainWindow to that color.

If you look at the code closely, you see that we call the configure command and send it $rb_value. Even though the default value of our Radiobutton group is "red", that doesn't mean that the background of the window has been set to red as well. We could also have set the background color using an explicit call to the set_bg routine, or back when we created the MainWindow.

The window we have created looks like Figure 4-12.

Figure 4-12

Figure 4-12. Radiobuttons that change the background color of the window

You might notice that for this example, rather than just setting a variable and waiting for the user to do something with it, we needed the Radiobutton to take action immediately when pressed. To do this, we used the -command option. Let's talk more about the -command option and callbacks in general.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.