for navigating through the list. As Figure 9-16 shows, shrinking this script’s window
cuts out part of the list but retains the scroll bar.
Figure 9-16. scrolledlist gets small
At the same time, you don’t generally want a scroll bar to expand with a window, so
be sure to pack it with just a fill=Y (or fill=X for a horizontal scroll) and not an
expand=YES. Expanding this example’s window in Figure 9-15, for instance, made the
listbox grow along with the window, but it kept the scroll bar attached to the right and
kept it the same size.
We’ll see both scroll bars and listboxes repeatedly in later examples in this and later
chapters (flip ahead to examples for PyEdit, PyMailGUI, PyForm, PyTree, and ShellGui
for more). And although the example script in this section captures the fundamentals,
I should point out that there is more to both scroll bars and listboxes than meets the
eye here.
For example, it’s just as easy to add horizontal scroll bars to scrollable widgets. They
are programmed almost exactly like the vertical one implemented here, but callback
handler names start with “x,” not “y” (e.g., xscrollcommand), and an
orient='horizontal' configuration option is set for the scroll bar object. To add both
vertical and horizontal scrolls and to crosslink their motions, you would use the fol-
lowing sort of code:
window = Frame(self)
vscroll = Scrollbar(window)
hscroll = Scrollbar(window, orient='horizontal')
listbox = Listbox(window)
# move listbox when scroll moved
vscroll.config(command=listbox.yview, relief=SUNKEN)
hscroll.config(command=listbox.xview, relief=SUNKEN)
# move scroll when listbox moved
listbox.config(yscrollcommand=vscroll.set, relief=SUNKEN)
listbox.config(xscrollcommand=hscroll.set)
See the image viewer canvas later in this chapter, as well as the PyEdit, PyTree, and
PyMailGUI programs later in this book, for examples of horizontal scroll bars at work.
Scroll bars see more kinds of GUI action too—they can be associated with other kinds
of widgets in the tkinter library. For instance, it is common to attach one to the Text
Listboxes and Scrollbars| 527