fill
-ingRemember that space is allocated to a widget from the currently available space left in the master widget by cutting off a complete slice from that space. It is often the case that the slice is bigger that the widget to be displayed in it.
There are further options for allowing a widget to fill the whole slice
allocated to it. This is done through the -fill option, which
can have one of four values: none
for no filling (default),
x
to fill horizontally only, y
to fill vertically only,
and both
to fill both horizontally and vertically at the same
time.
Filling is useful, for example, for creating buttons that are the same size even though they display texts of differing lengths. To take our button example again, the following code produces three buttons, one on top of each other, but of the same size:
button .b1 -text b1 button .b2 -text "hello world" button .b3 -text b3 pack .b1 .b2 .b3 -fill x
fill
For Evenly Sized WidgetsHow does this work? The width of the toplevel windows is dictated by
button .b2
because it has the widest text. Because the three
buttons are packed from top to bottom, then the slices of space
allocated to them are cut progressively straight along the top of the
remaining space. i.e. each widget gets a horizontal slice of space the
same width cut from the top-level widget. Only the wide button
.b2
would normally fit the whole width of its slice. But by
allowing the other two widgets to fill horizontally, then they will also
take up the whole width of their slices. The result: 3 buttons stacked
on top of each other, each with the same width, although the texts they
display are not the same length.
A further common example is adding a scrollbar to a listbox.
The trick is to get the scrollbar to size itself to the listbox;
see also library('tcltk/examples/ex9a.tcl')
:
listbox .l scrollbar .s pack .l .s -side left
So far we have a listbox on the left and a tiny scrollbar on the right. To get the scrollbar to fill up the vertical space around it add the following command:
pack .s -fill y
Now the display looks like a normal listbox with a scrollbar.
Why does this work? They are packed from the left, so first a large
vertical slice of the master is given to the listbox, then a thin
vertical slice is given to the scrollbar. The scrollbar has a small
default width and height and so it does not fill the vertical space of
its slice. But filling in the vertical direction (through the
pack .s -fill y
command) allows it to fill its space, and so
it adjusts to the height of the listbox.