Tkinter dynamic event binding for multiple tags

Viewed 545

Trying to bind an event to multiple text tags in tkinter. Basically a user inputs a text, and the text is re-written in the text input with every word as tags so that when the user clicks on a word, the word is picked up.

def check_input():
   user_input = text.get('1.0', END)
   text.delete("1.0",END)
   u = user_input.split()  
   tags = []
   for i,j in enumerate(u):
       tags.append('tag'+str(i))
       text.tag_config("tag"+str(i), foreground="blue")
       text.insert(END, j+" ", "tag"+str(i))


   for t in tags:
       text.tag_bind(t, "<Button-1>", lambda e:click(e, t))

Looping through all tags and trying to bind the click event does not work, it only binds to the last tag. How do I dynamically bind the event to multiple tags ?

1 Answers

You are calling callback(e, t) when binding a tag.

Instead, you should use a lambda function to pass the correct arguments and bind them to each tag:

lambda event, t=t: callback(event, t)
Related