Grid

The grid method of placing widgets is analogous to thinking of the window being divided up, as in a spreadsheet, into a number of rows and columns, and positioning a widget in a particular cell. The basic use is as
$widget1->grid( [$widget2, $widget3, ...], [ option => value]);
which creates one row consisting of the named widgets. Subsequent calls to grid will result in more rows being created. For example, the following program,
#!perl
# file grid1.pl
use Tk;
use strict;
use warnings;
my $mw = MainWindow->new;
$mw->title('Grid Example');
my $title = $mw->Label(-text => 'Example of using grid on several widgets');
my $cb1 = $mw->Checkbutton(-text => 'Checkbutton 1');
my $button = $mw->Button(-text => 'A Button');
my $label = $mw->Label(-text => 'A Label');
my $cb2 = $mw->Checkbutton(-text => 'Checkbutton 2');
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
$title->grid;
$cb1->grid($cb2);
$label->grid($button);
$exit->grid;
MainLoop;
produces the following output:

Figure 2.7: An example of the use of grid
Image grid1

As with pack, the options available to grid allow more control over the placement of the widgets. The available options, as described in the Tk documentation, are listed below.

As an example, the previous program with the following grid options,
#!perl
# file grid2.pl
use Tk;
use strict;
use warnings;
my $mw = MainWindow->new;
$mw->title('Grid Example');
my $title = $mw->Label(-text => 'Example of using grid on several widgets');
my $cb1 = $mw->Checkbutton(-text => 'Checkbutton 1');
my $button = $mw->Button(-text => 'A Button');
my $label = $mw->Label(-text => 'A Label');
my $cb2 = $mw->Checkbutton(-text => 'Checkbutton 2');
my $exit = $mw->Button(-text => 'Exit',
                       -command => [$mw => 'destroy']);
$title->grid(-columnspan => 2);
$cb1->grid($cb2, -sticky => 'w');
$label->grid($button, -columnspan => 2, -sticky => 'w');
$exit->grid(-columnspan => 2);
MainLoop;
produces the following window.

Figure 2.8: A second example of the use of grid
Image grid2

As with pack, we will examine more of the options to grid in the later applications.

Randy Kobes 2003-11-17