Label

A label widget is a non-interactive widget used to simply put some informative text in the window. This is normally used to place some short words of explanation for some particular aspect of the application. As very verbose explanations tend to clutter a window, these widgets should be used sparingly - short but useful labels on various buttons, used in a consistent manner across the application, should make an explanatory text label redundant. The basic syntax for creating a label widget is
my $label = $mw->Label( [ option => value ] );
Two basic options are We give two examples of its use. The first,
#!perl
# file label.pl
use Tk;
use strict;
use warnings;
my $mw = MainWindow->new;
$mw->title('Label');
my $hello = $mw->Label(-text => 'Greetings!');
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
$hello->pack(-side=>'top');
$exit->pack(-side => 'bottom');
MainLoop;
is an example of a fixed label, using the -text option. This is illustrated in the figure below.

Figure 3.4: Example of a label widget
Image label

The second example,

#!perl
# file label1.pl
use Tk;
use strict;
use warnings;
my $greeting = 'Hello';
my $mw = MainWindow->new;
$mw->title('Label');
my $label = $mw->Label(-textvariable => \$greeting);
my $hello = $mw->Button(-text => 'Hello',
                        -command => \&hello);
my $goodbye = $mw->Button(-text => 'Goodbye',
                          -command => \&goodbye);
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
$label->pack(-side=>'top');
$exit->pack(-side => 'bottom', -fill => 'both');
$hello->pack(-side=>'left');
$goodbye->pack(-side=>'right');
MainLoop;
sub hello {
  $greeting = 'Hello';
}
sub goodbye {
  $greeting = 'Goodbye';
}
is an example of using the -textvariable option to display a variable message. This appears in the figure below.

Figure 3.5: Another example of a label widget
Image label1

The two buttons, $hello and $goodbye, simply change the value of $greeting, and when clicked subsequently change the label displayed.

Randy Kobes 2003-11-17