1

I have the following code to create a group of labels, with label_click_handler running when one of them is clicked:

def label_click_handler(i):
    print("Label " + str(i) + " pressed")
    # etc.

for i in range(10):
    label = Label(text="Label " + str(i))
    label.place(x=i*50, y=0)
    label.bind("<Button-1>", lambda e:label_click_handler(i))

My issue is that clicking on any of the buttons will print the message:

Label 9 pressed

So the value of 9 (last in the range) is passed through to label_click_handler no matter which button is pressed.

How can I make the number of the button pressed get passed to label_click_handler?

1 Answers1

0

Set i=i in the lambda function so i default value in function is set to the current i value.


def label_click_handler(i):
    print("Label " + str(i) + " pressed")
    # etc.

for i in range(10):
    label = Label(text="Label " + str(i))
    label.place(x=i*50, y=0)
    label.bind("<Button-1>", lambda e,i=i:label_click_handler(i))
codester_09
  • 5,622
  • 2
  • 5
  • 27