-1

I have a loop which creates a list of buttons and grids them to form a square depending on the size from the user and I want each button to pass the loop index to the same command/function, but when the button is pressed it always passes the last value of the loop index so if it was for i in range(0,5) it will pass 4 on all the button presses. I tried copy.copy and copy.deepcopy and they didn't make a difference. Here is the loop that creates the button list:

for x in range(0,size): btnlist[x]=(tk.Button(text=x,activebackground="black")) btnlist[x].grid(column=int(x%math.sqrt(size)),row=int(x/math.sqrt(size))+1) btnlist[x].config(command=lambda:btnpress(x))

1 Answers1

0

You can use functools.partial instead of the lambda expression:

from functools import partial

for x in range(0,size):
    btnlist[x]=(tk.Button(text=x,activebackground="black")) 
    btnlist[x].grid(column=int(x%math.sqrt(size)),row=int(x/math.sqrt(size))+1) 
    btnlist[x].config(command=partial(btnpress, x))

slarag
  • 153
  • 8
  • Also check out [this post](https://stackoverflow.com/questions/10865116/tkinter-creating-buttons-in-for-loop-passing-command-arguments). This is basically the same question (duplicate). – slarag May 16 '22 at 07:37