Which dynamically created object called the function?
Question: I am making a python app with a Tkinter GUI. So far it has some dynamically
created listboxes which I will link all to one scrollbar. I need a way to let
`yscroll()` know which listbox has been scrolled. Passing the `i` variable to
`yscroll()` does not work.

    
    
    from Tkinter import *
    
    class MyApp(Tk):
        def __init__(self):
            Tk.__init__(self)
            self.title(' - My App - ')
    
            self.listboxes = []
            for i in xrange(5):
                lb = Listbox(self, yscrollcommand=lambda i, *args: self.yscroll(i, *args))
                for x in xrange(30):
                    lb.insert('end', x)
    
                lb.pack(fill='y', side='left')
                self.listboxes.append( lb )
    
            self.scrollbar = Scrollbar(self, orient='vertical')
            self.scrollbar.pack(side='right', fill='y')
    
        def yscroll(self, i, *args):
            print i
            print args
    
    ma = MyApp()
    ma.mainloop()
    


Answer: It seems like the [usual recipe for using a variable from a loop in a
lambda](http://stackoverflow.com/a/19837683/1639625) does not work properly
when used together with parameter unpacking with `*args`. But since `*args`
seems to always consist of two values in this case (the beginning and the end
of the viewport, unless I'm mistaken), you could rewrite your `lambda` like
this:

    
    
    lb = Listbox(self, yscrollcommand = lambda x, y, i=i: self.yscroll(i, x, y))
    

Or you can create a sort of "meta lambda", creating a lambda with the correct
value for `i`

    
    
    make_callback = lambda i: lambda *args: self.yscroll(i, *args)
    lb = Listbox(self, yscrollcommand = make_callback(i))
    

Both will bind `i` to the value of `i` in the iteration when the `lambda` was
defined.

