4.2. Details of Boxes

Because of this flexibility, packing boxes in GTK can be confusing at first. There are a lot of options, and it's not immediately obvious how they all fit together. In the end, however, there are basically five different styles. Figure 4.1 illustrates the result of running the program packbox.py with an argument of 1:
 

Figure 4.1 Packing: Five Variations


Each line contains one horizontal box (hbox) with several buttons. The call to pack is shorthand for the call to pack each of the buttons into the hbox. Each of the buttons is packed into the hbox the same way (i.e., same arguments to the pack_start() method).

This is an example of the pack_start() method.
 
box.pack_start(child, expand, fill, padding)

box is the box you are packing the object into; the first argument is the child object to be packed. The objects will all be buttons for now, so we'll be packing buttons into boxes.

The expand argument to pack_start() and pack_end() controls whether the widgets are laid out in the box to fill in all the extra space in the box so the box is expanded to fill the area allotted to it (TRUE); or the box is shrunk to just fit the widgets (FALSE). Setting expand to FALSE will allow you to do right and left justification of your widgets. Otherwise, they will all expand to fit into the box, and the same effect could be achieved by using only one of pack_start() or pack_end().

The fill argument to the pack methods control whether the extra space is allocated to the objects themselves (TRUE), or as extra padding in the box around these objects (FALSE). It only has an effect if the expand argument is also TRUE.

When creating a new box, the function looks like this:
 
hbox = GtkHBox(homogeneous, spacing)
vbox = GtkVBox(homogeneous, spacing)

The homogeneous argument to GtkHBox() and GtkVBox() controls whether each object in the box has the same size (i.e., the same width in an hbox, or the same height in a vbox). If it is set, the pack routines function essentially as if the expand argument was always turned on.

What's the difference between spacing (set when the box is created) and padding (set when elements are packed)? Spacing is added between objects, and padding is added on either side of an object. Figure 4.2 illustrates the difference; pass an argument of 2 to packbox.py:

Figure 4.2 Packing with Spacing and Padding

Figure 4.3 illustrates the use of the pack_end() method (pass an argument of 3 to packbox.py). The label "end" is packed with the pack_end() method. It will stick to the right edge of the window when the window is resized.

Figure 4.3 Packing with pack_end()


Here is the code used to create the above images. It's commented fairly heavily so I hope you won't have any problems following it. Run it yourself and play with it.