I am developing a Text based application using Python Tkinter, In my Text widget created some words are tag_configured, on double clicking mouse on that tagged words selection appears with blue color, how can I get this selected text for further processing, Code as follows.........
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 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 someone guide me on how to solve this error.
Exactly like tobias_k mentions in his comment, the order in which the event bindings are executed is key here, because you are trying to get the selected text before the text is actually selected. You can see the order of binding execution using the bindtags()
widget method. When you do this for a Text widget you will see something like
('.38559496', 'Text', '.', 'all')
Which means that the order, from left to right, of binding event execution is so that first events that are unique to this specific widget are evaluated, then those specific to the widget class, then those to your root window and finally everything else on application level (source).
Your double-click event is on widget level, since it is applied only to that specific widget, but the actual selection of the text is an event on the Text class level. Therefore, you will have to rearrange the order so that the class events come before the widget events. You can get the order by calling bindtags
without 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 makes sure that the selection of the text is performed before you try to read the selection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With