Listbox

Checkbuttons and radiobuttons are useful when there are just a few (set) options available to a user. However, when the number of options increases, such buttons tend to clutter the window. Which country do you live in? What file would you like to open? In such cases the listbox widget becomes useful. The syntax for creating a listbox is
my $lb = $mw->Listbox( [ option => value ] );
A basic option is As well as this option, there are some basic methods that are used to add items to a listbox, retrieve the items that were selected, and to clear the list of selections: An example of the use of the listbox follows.
#!perl
# file lb.pl
use Tk;
use strict;
use warnings;
my $lb_value = 'not given';
my $message = "Your favourite programming language is $lb_value";
my @languages = qw(Perl C C++ Java Pascal Fortran Basic);
my $mw = MainWindow->new;
$mw->title('Listbox');
my $label = $mw->Label(-textvariable => \$message);
my $enter = $mw->Label(-text => 'Select your favourite languages');
my $lb = $mw->Listbox(-selectmode => 'multiple');
$lb->insert('end', sort @languages);
my $show = $mw->Button(-text => 'Show selections',
                       -command => \&display);
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
$label->pack;
$enter->pack;
$lb->pack;
$show->pack;
$exit->pack;
MainLoop;
sub display {
  my @selections = $lb->curselection;
  $message = "You selected: \n";
  foreach (@selections) {
    $message .= $lb->get($_) . "\n";
  }
  $lb->selectionClear(0, 'end');
}
The window is illustrated below.

Figure 3.10: Example of a listbox widget
Image lb

Here the listbox $lb is populated with the array @languages, and a string $message is used as the text for the label $label. The button $show invokes the display subroutine which first finds the indices of the selected items, and then appends the values to the $message string through the $lb->get method. The selections are then cleared.

Randy Kobes 2003-11-17