[Tutor] Binding ListBox

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jul 21 17:13:41 CEST 2006



> I am learning Python 2.4 with Tkinter. I have a series of radio buttons 
> that I want to bind to their own individual listbox in order to narrow 
> down a selection process.

Hi Joe,

Ok, are you familiar with callbacks?  According to:

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

you can introduce a callback that will fire off when the user does a 
Radiobutton selection.  Do you have much experience using functions as 
values?



> I just don't seem to grasp how to call up the approiate box to it's 
> proper radiobutton.

If the "callback" we bind to to the radio button could only remember the 
listbox, we'd be in business.  It turns out that this is possible if we 
build a function within a function:

####################
def make_adder(n):
     def f(x):
         return x + n
     return f
####################


For example:

#########################
>>> add1 = make_adder(1)
>>> sub1 = make_adder(-1)
>>> add1(3)
4
>>> sub1(3)
2
#########################


This mechanism (lexical scope) is very useful, especially in GUI 
programming.  In your problem, one could imagine making a a function that 
takes in a listbox and returns a new Radiobutton that "remembers" its 
listbox.

########################################################
def makeRadioButtonWithListbox(root, listbox):
     def callback():
         # ... This callback has access to the listbox
     b = Radiobutton(root, text="text", command=callback)
     return b
########################################################

It's the same technique.  In this way, we can create radio buttons that 
have a way of getting at the listbox.


More information about the Tutor mailing list