With certain widgets, such as the listbox and text, it may happen that the information to be displayed exceeds the space available. This will probably happen, for example, if you're loading a file in the main window of a text editor. When this occurs, you have two options - make the widget bigger, or use a scrollbar. Making the widget bigger is often not the best solution - it may overwhelm the desktop, or indeed may not be even possible. You would probably then resort to a scrollbar.

Perl Tk has two methods of making scrollbars. One is through the use of the Scrollbar widget, created, as with other widgets, as

my $scrollbar = $mw->Scrollbar( [ option => value ] );
The other method, which is easier but not as configurable, is through the use of Scrolled method, as in
my $widget = $mw->Scrolled('WidgetName', 
                           -scrollbars => 'value',  
                           [ option => value ] );
Here, ``WidgetName'' is then name of a widget, such as ``Text'', ``Listbox'', or ``Entry''. The ``value'' of the -scrollbars option is some combination of ``n'', ``s'', ``e'', ``w'', ``on'', ``os'', ``oe'', or ``ow''. The ``o'' preceding the direction means to make the scrollbar optional, so that it will be displayed only if needed. The other options in the above are those for the particular widget itself. Note that, to avaoid some complaints from Tk, if you use a combination of ``n'' or ``s'' with ``e'' or ``w'', use the ``n'' or ``s'' indicator first.

In this Chapter we confine ourselves to the Scrolled method of creating scrollable widgets. As an example of a scrolled widget, we will create a listbox of the names of files in the current directory. The code is as follows.

#! file
use Tk;
use strict;
use warnings;
opendir(DIR, '.') or die "Cannot open '.' for reading: $!\n";
my @files = grep {! -d } readdir DIR;
closedir DIR or die  "Cannot close '.': $!\n";
my $mw = MainWindow->new;
my $label = $mw->Label(-text => 'File listing');
my $lb = $mw->Scrolled('Listbox',
                       -scrollbars => 'osow',
                       -selectmode => 'single');
$lb->insert('end', sort @files);
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
Here the scrollable list box is created with the Scrolled method, with the -scrollbars option ``osow'' meaning to create scollbars at the bottom and to the right of the listbox, as needed. A screenshot of this window appears below.

Figure 3.17: Example of a scrollable listbox
Image scroll

Randy Kobes 2003-11-17