-1

Here is my code:

buttons=[]
for i in range(100):
    buttons.append(Button(parent,text="0",command=lambda:[change(i)])
def change(i):
    buttons[i]["text"]="1"

but as finally, the i will go to 99, I could only change the last button no matter which button I clicked. So I wonder is there any good way to do so?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Cai Xuran
  • 1
  • 1
  • Seems like this is because of [Late Binding Closures](https://docs.python-guide.org/writing/gotchas/#late-binding-closures). Can you try `command=lambda i=i:[change(i)]` instead? – Abdul Niyas P M Dec 13 '20 at 16:16

1 Answers1

0

The solution is very easy Just change the command by below command

command = lambda i=i:change(i)

This will do the job for you. Your solution not worked as expected because python passes the last value of i And hence to resolve this problem The above command is the solution. Here lambda is given argument(that is i) at the same time when each execution of loop is going and then that i is passed to change function which is why it worked

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343