How to get selected text from Python Tkinter Text widget

I am developing a text based application using Python Tkinter. In my text widget some tag_configured words are generated, when I double click on this marked selection of words blue color appears, how can I get this selected text for further processing, Code like this .........

self.area.tag_configure('errorword',font=('MLU-Panini', 15,foreground="black",underline=True)

self.area.tag_bind("errorword","<Double-Button-1>",self.mouse_click,add=None)

def mouse_click(self,event):

        errorstr=self.area.get(tk.SEL_FIRST,tk.SEL_LAST)
        print("mmmmmm",errorstr)

      

Shows an error

File "C:\Python34\lib\tkinter\__init__.py", line 3082, in get
    return self.tk.call(self._w, 'get', index1, index2)
_tkinter.TclError: text doesn't contain any characters tagged with "sel"

      

.................................................. .....................

Can anyone help me solve this error.

+3


source to share


1 answer


Just as tobias_k mentions in his comment , the order in which event bindings are done is key here because you are trying to get the selected text before the text is actually selected. You can see the order in which the binding is performed using the widget method bindtags()

. When you do this for the text widget, you will see something like

('.38559496', 'Text', '.', 'all')

      

This means the left-to-right ordering associated with the execution of the binding in such a way that the first events that are unique to that particular widget are evaluated, then those that are specific to the widget class, and then to your root window, and finally all otherwise at the application level ( source ).



Your double click event is at the widget level as it only applies to that specific widget, but the actual text selection is an event at the Text class level. Therefore, you will have to reorder so that class events come before widget events. You can get the order by calling bindtags

with no arguments, and then define a new order by calling it again with a tuple containing the order:

order = self.area.bindtags()
self.area.bindtags((order[1], order[0], order[2], order[3]))

      

This ensures that the text selection is done before you try to read the selection.

+2


source







All Articles