lambda working oddly with tkinter lambda working oddly with tkinter tkinter tkinter

lambda working oddly with tkinter


Ah, scoping. When you do this:

command=lambda: self.addkey(str(i))

You're not "resolving" the i to a number right there and then. You're just telling the lambda to reference i when it's invoked, afterwards.

At any time past the end of the for loop, i = 3 (last value), so all of your lambdas get 3 when they ask for i.

If I'm not mistaken, you can add a function as means of indirection, and it will appropriately "capture" i from the surrounding scope.

def add_key_f(i):    return lambda self: self.addkey(i)