[Tutor] Help

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 10 Oct 2001 11:12:34 -0700 (PDT)


On Tue, 9 Oct 2001, Glauco Silva wrote:

> I would like to know how i can to do one Scrollbar to be linked with
> two Listbox if it's possible . Thank you Glauco

According to the documentation on the Scrollbar widget:

    http://www.pythonware.com/library/tkinter/introduction/scrollbar.htm

we can connect a Scrollbar to a single listbox by configuring it.  If we
look at their example at:

http://www.pythonware.com/library/tkinter/introduction/x7583-patterns.htm

    scrollbar.config(command=listbox.yview)


A scrollbar interacts with its environment by calling back the "command"
function whenever we fiddle with the scrollbar. At first glance, it looks
like a scrollbar can only be connected to one callback, so that appears to
limit us to one widget.

However, nothing stops us from having that callback do something to two
things!  Here's a small utility class I cooked up to make this easier:
it's a callback-maker that ties two preexisting callbacks together in one
bundle:

###
class TieTwoCallbacks:
    def __init__(self, callback1, callback2):
        self.callback1, self.callback2 = callback1, callback2

    def __call__(self, *args):
        apply(self.callback1, args)
        apply(self.callback2, args)
###


To get a feel for what this is doing, here's a small sample run with some
non-GUI elements:

###
>>> def greeting(name): print "hello", name
... 
>>> def farewell(name): print "goodbye", name
...
>>> a_chance_meeting = TieTwoCallbacks(greeting, farewell)
>>> a_chance_meeting('glauco silva')
hello glauco silva
goodbye glauco silva
###



With this, we can imagine configuring your scrollbar like this:

###
composite_callback = TieTwoCallbacks(listbox1.yview,
                                     listbox2.yview)
scrollbar.config(command=composite_callback)
###

so that when we move the scrollbar, that scrollbar will call our
composite_callback.  And since the composite_scrollback knows about
listbox1.yview and listbox2.yview, it can yell at both of them.




We can have even more fun: once we have something that ties together two
things, we can tie together multiple things!

###
>>> def handshake(dont_care): print "Let's shake!"
... 
>>> another_chance_meeting = TieTwoCallbacks(greeting,
...                              TieTwoCallbacks(handshake, farewell))
>>> another_chance_meeting('guido')
hello guido
Let's shake!
goodbye guido
###


However, this is completely untested code --- I haven't seen how this will
work with listboxes.  *grin* If you have questions about the code above,
please feel free to ask.