I want to create multiple clickable labels in a for-loop. The labels are structured grid-like with a row and col attribute. If I click the label, the row and col of the clicked label should be printed with the print_it() function.
The problem is if I click any label, the output is always the last defined row/col (2,2) in this case. How can I fix it, so the correct row/col gets printed?
Here is a code example to reproduce:
from tkinter import *
def print_it(row, col):
print(row, col)
root = Tk()
sizex = 700
sizey = 400
posx = 0
posy = 0
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
canvas_area = Canvas(root)
canvas_area.grid(row=1, column=1)
labels = []
for row in range(3):
for col in range(3):
labels.append(Label(canvas_area, text=f"Row, Col: {row},{col}", bd=0))
labels[-1].grid(row=row, column=col)
labels[-1].bind(
f"<Button-1>",
lambda e: print_it(row, col),
)
root.mainloop()