'Python. Passing a different value for each button command to the same function [duplicate]

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))



Solution 1:[1]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 slarag