40.3.5 Geometry Managers

So far we have described each of the Tk widgets but have not mentioned how they are arranged to be displayed. Tk separates the creating of widgets from the way they are arranged for display. The “geometry” of the display is handled by a “geometry manager”. A geometry manager is handed the set of widgets to display with instructions on their layout. The layout instructions are particular to each geometry manager.

Tk comes with three distinct geometry managers: grid, place, and pack. As might be expected the grid geometry manager is useful for creating tables of widgets, for example, a table of buttons.

The place geometry manager simply gives each widget an X and Y coordinate and places them at that coordinate in their particular parent window.

The pack geometry manager places widgets according to constraints, like “these three button widgets should be packed together from the left in their parent widget, and should resize with the parent”.

(In practice the grid and pack geometry managers are the most useful because they can easily handle events such as resizing of the toplevel window, automatically adjusting the display in a sensible manner. place is not so useful for this.)

Each container widget (the master) has a geometry manager associated with it, which tells the container how to display its sub-widgets (slaves) inside it. A single master has one and only one kind of geometry manager associated with it, but each master can have a different kind. For example, a frame widget can use the packer to pack other frames inside it. One of the slave frames could use the grid manager to display buttons inside it itself, while another slave frame could use the packer to pack labels inside it itself.