Checkbutton

A checkbutton widget is used to allow the user to set an option for which the choices can be phrased as the answer to a ``yes/no'' type of question. Do you want to be added to our mailing list? Do you want fries with that? The basic syntax to create a checkbutton is
my $cb = $mw->Checkbutton( [ option => value ] );
Some basic options are We give two examples of its use. The first,
#!perl
# file cb.pl
use Tk;
use strict;
use warnings;
my $cb_value = 'off';
my $message = "Checkbutton is $cb_value";
my $mw = MainWindow->new;
$mw->title('Checkbutton');
my $label = $mw->Label(-textvariable => \$message);
my $cb = $mw->Checkbutton(-text => 'Checkbutton',
                          -variable => \$cb_value,
                          -onvalue => 'on',
                          -offvalue => 'off');
my $show = $mw->Button(-text => 'Show status',
                       -command => \&display);
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
$cb->pack;
$label->pack;
$show->pack;
$exit->pack;
MainLoop;
sub display {
  $message = "Checkbutton is $cb_value";
}
associates the status of the checkbutton $cb with the variable $cb_value. This window is illustrated below.

Figure 3.6: Example of a checkbutton widget
Image cb

This variable has the value on when the checkbutton is checked, and off when the button is not selected. The $show button, when clicked, will change the value of the $message string, which contains the current value of $cb_value, and this will be reflected in the text associated with the label $label.

The second example,

#!perl
# file cb1.pl
use Tk;
use strict;
use warnings;
my $cb_value = 'off';
my $message = "Checkbutton is $cb_value";
my $mw = MainWindow->new;
$mw->title('Checkbutton');
my $label = $mw->Label(-textvariable => \$message);
my $cb = $mw->Checkbutton(-text => 'Checkbutton',
                          -variable => \$cb_value,
                          -onvalue => 'on',
                          -offvalue => 'off',
                          -command => \&display);
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
$cb->pack;
$label->pack;
$exit->pack;
MainLoop;
sub display {
  $message = "Checkbutton is $cb_value";
}
is illustrated below.

Figure 3.7: Another example of a checkbutton widget
Image cb1

This example is similar to the first, but the command to change the $message string (again containing the current value of $cb_value) is associated with the checkbutton $cb itself, through the -command option and the associated display subroutine. In this case the text of the label of $label will be updated as soon as the status of the checkbutton changes.

Randy Kobes 2003-11-17