pythontkinter

Clickable text in ScrolledText widget - how do I extract the text that was clicked?


Title says it all, really. I am writing a simple address book as part of a larger program, displaying details in a ScrolledText widget.

self.contact_list = ScrolledText(
    self,
)
self.contact_list.grid(row=1, column=0, sticky='nsew')
self.contact_list.tag_bind('clickable', '<Double-1>', self.edit_entry)

Each person's entry is displayed in a single row, which has been tagged as 'clickable', followed by a non-tagged \n.

entry = f'{name:<20} {phone:<15} {email:<30}'
self.contact_list.insert(tk.END, entry, 'clickable')
self.contact_list.insert(tk.END, '\n')

Double clicking each entry does call the edit_entry funtion - confirmed by simply printing a message when the function is called. And that's where I come to a grinding halt. I cannot work out - or find out - how to extract the line of text that's just been double clicked. Professor Google has been notably unhelpful (or, maybe, I just don't know the right search term).


Solution

  • There is a special tag current which refers to the index of the cursor click, so you can use this to find the start and end of the clicked line:

    s = self.contact_list.index('current linestart')
    e = self.contact_list.index('current lineend')
    line_content = self.contact_list.get(s, e)
    

    However I would suggest to use ttk.Treeview instead of ScrolledText for such kind of data.