tkinter creating buttons in for loop passing command arguments

Change your lambda to lambda i=i: self.open_this(i).

This may look magical, but here’s what’s happening. When you use that lambda to define your function, the open_this call doesn’t get the value of the variable i at the time you define the function. Instead, it makes a closure, which is sort of like a note to itself saying “I should look for what the value of the variable i is at the time that I am called“. Of course, the function is called after the loop is over, so at that time i will always be equal to the last value from the loop.

Using the i=i trick causes your function to store the current value of i at the time your lambda is defined, instead of waiting to look up the value of i later.

Leave a Comment