'Python tkinter button lambda function using incorrect arguments [duplicate]
So, I have this code:
root = Tk()
root.geometry("600x600")
for i in range(8):
for j in range(8):
Button(root, text=f"{i+1}, {j+1}", command=lambda:[print(i+1,j+1)]).grid(row=i, column=j)
root.mainloop()
which Is what I wanted, but when I press on the button I want it to print to the console what Is written on the button (e.g. I press 0,4 and it prints 0,4), but no matter what button I press, it prints 7 7.
Any possible fixes?
Solution 1:[1]
I have worked it out.
I used some arguments in the lambda function so they are frozen when the Button() is made.
It ended up looking like this:
root = Tk()
root.geometry("600x600")
for i in range(8):
for j in range(8):
Button(root, text=f"{i}, {j}", command=lambda x=i, y=j:[print(x,y)]).grid(row=i+1, column=j+1)
root.mainloop()
And it worked as mentioned above
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 | AJDP |

