Main Content

Tk - laying out your GUI with frames, pack and grid

Archive - Originally posted on "The Horse's Mouth" - 2006-06-30 06:37:05 - Graham Ellis

Using Tk (in Tcl or in Perl), you create a number of components that you want to display as part of your GUI (Graphic User Interface) using commands such as button, label and canvas. These components are known as widgets.

Once you've created your widgets, you need to use a geometry manager to tell the program how to display them in relation to each other - and there are three such geometry managers.

pack allows you to place your widgets in a row or column

grid allows you to place your widgets in a matrix

place is rarely used, and gives you the ability to place widgets by pixel or by the proportion of the way across the window that you want them to appear.

Pack, grid and place don't on their own provide you with the full flexibility to lay out more complex windows. For a complex layout, you'll split the parent window into a series of frames which you will pack or grid, and then you'll pack or grid the individual widgets into the frames. If necessary, you can nest frames several layers deep.

If you're a designer laying out your GUI, where should you start? With a sketch on a sheet of paper (or a whiteboard). Look to see if the WHOLE layout can be achieved by using a single pack or grid ... if not, look for places where you can draw a line between widgets RIGHT ACROSS the window. These lines are the first level of splitting you GUI down into frames.

If you can draw lines RIGHT ACROSS, both horizontally and vertically, then you'll use the grid geometry manager for your root window. If you can draw ONLY horizontal or vertical lines, then you'll use pack.

Repeat the design process, frames within frames, until each of your remaining subframes is a simple grid or pack in its own right, or is a single widget.