Tkinter Text widget - Use clicked text in event function Tkinter Text widget - Use clicked text in event function tkinter tkinter

Tkinter Text widget - Use clicked text in event function


You can use individual tag for every clicked text and then you can send it as argument to binded function

import tkinter as tkdef callback(event, tag):    print(event.widget.get('%s.first'%tag, '%s.last'%tag))root = tk.Tk()text = tk.Text(root)text.pack()text.tag_config("tag1", foreground="blue")text.tag_bind("tag1", "<Button-1>", lambda e:callback(e, "tag1"))text.insert(END, "first link", "tag1")text.insert(END, " other text ")text.tag_config("tag2", foreground="blue")text.tag_bind("tag2", "<Button-1>", lambda e:callback(e, "tag2"))text.insert(END, "second link", "tag2")root.mainloop()

EDIT:

I found how to convert mouse position and find clicked tag so it doesn't need individual tags.

Python TKinter get clicked tag in text widget

import tkinter as tkdef callback(event):    # get the index of the mouse click    index = event.widget.index("@%s,%s" % (event.x, event.y))    # get the indices of all "adj" tags    tag_indices = list(event.widget.tag_ranges('tag'))    # iterate them pairwise (start and end index)    for start, end in zip(tag_indices[0::2], tag_indices[1::2]):        # check if the tag matches the mouse click index        if event.widget.compare(start, '<=', index) and event.widget.compare(index, '<', end):            # return string between tag start and end            print(start, end, event.widget.get(start, end))root = tk.Tk()text = tk.Text(root)text.pack()text.tag_config("tag", foreground="blue")text.tag_bind("tag", "<Button-1>", callback)text.insert(END, "first link", "tag")text.insert(END, " other text ")text.insert(END, "second link", "tag")root.mainloop()


You shouldn't create a second instance of Tk. If you need a popup window, create an instance of Toplevel. You also don't need to call mainloop a second time.

You can get the index that was clicked on by using the x,y coordinate that you clicked on. For example: text.index("@%d,%d" % (event.x, event.y))