Geometry Managers

Creating widgets and determining how to display them are done with separate commands. You can create a widget with one of the widget creation methods (such as Button, Canvas, etc.), but you display them using a geometry manager. The three geometry managers are pack, grid, and place. pack is by far the most commonly used.

You can either pack a widget as you create it, or you can create the widget object and pack it separately. For example, the previous "Hello World!" example might have read:

#!/usr/bin/perl -w use Tk; my $mw = MainWindow->new; $button = $mw->Button(-text => "Hello World!", -command =>sub{exit}); $button->pack; MainLoop;


The pack Geometry Manager

With the pack geometry manager, widgets cannot overlap or cover each other, either partially or completely. Once a widget is packed into a window, the next widget is packed in the remaining space around it. pack sets up an "allocation rectangle" for each widget, determined by the dimensions of the parent window and the positioning of the widgets already packed into it. This means that the order in which you pack your widgets is very important.

pack places widgets at the top center of the allocation rectangle. However, you can use options to pack to control where a widget is placed and how much padding is placed around it. Options for pack are:

Pack methods

The following methods are associated with pack:

The grid Geometry Manager

The grid geometry manager divides the window into a grid composed of columns and rows starting at 0,0 in the upper left-hand corner. The resulting grid resembles a spreadsheet, with each widget assigned a cell according to the options to grid. To create a grid, create a frame that is packed inside the parent window and then grid the widgets within the frame.

You can specify explicit rows and columns using options to grid. However, if several widgets are meant to appear in the same row, you can use a single grid command with a list of widgets rather than calling grid for each one. The first widget invokes the grid command, and all other widgets for that column are specified as options to grid. Any subsequent grid commands increment the row by one and start again.

You can use special characters as placeholders:

Options to grid are:

Grid methods

The following methods are associated with grid:

The Place Geometry Manager

The place geometry manager lets you position a window at explicit x,y coordinates. With place, you can overlap widgets, which isn't allowed with grid or pack. For example, to position a button widget at the upper left corner of a window:

$button->place(-x => 0, -y => 0);


Options to place are:

The following methods are associated with place: