pythonware.com products ::: library ::: search ::: daily Python-URL!
   

Patterns

Back   Next   

 Patterns

The Scrollbar widget is almost always used in conjunction with a Listbox, Canvas, or Text widget. Horizontal scrollbars can also be used with the Entry widget.

To connect a vertical scrollbar to such a widget, you have to do two things:

  1. Set the widget's yscrollcommand callbacks to the set method of the scrollbar.

  2. Set the scrollbar's command to the yview method of the widget.

Example 40-1. Connecting a scrollbar to a listbox

# scrollbar-example-1.py

from Tkinter import *

root = Tk()

scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)

listbox = Listbox(root, yscrollcommand=scrollbar.set)
for i in range(1000):
    listbox.insert(END, str(i))
listbox.pack(side=LEFT, fill=BOTH)

scrollbar.config(command=listbox.yview)

mainloop()

When the widget view is modified, the widget notifies the scrollbar by calling the set method. And when the user manipulates the scrollbar, the widget's yview method is called with the appropriate arguments.

Adding a horizontal scrollbar is as simple. Just use the xscrollcommand option, and the xview method.

Back   Next