简体   繁体   English

如何从Python Tkinter Text小部件中获取所选文本

[英]How to get selected text from Python Tkinter Text widget

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......... 我正在使用Python Tkinter开发一个基于文本的应用程序,在我的Text小部件中创建了一些单词是tag_configured,双击鼠标时,标记的单词选择显示为蓝色,如何获取此选定文本以供进一步处理,代码如下。 ........

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. 正如在评论中提到的tobias_k一样,事件绑定的执行顺序在这里是关键,因为您试图在实际选择文本之前获取所选文本。 You can see the order of binding execution using the bindtags() widget method. 您可以使用bindtags()窗口小部件方法查看绑定执行的顺序。 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. 您的双击事件位于窗口小部件级别,因为它仅应用于该特定窗口小部件,但实际选择的文本是Text类级别的事件。 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: 您可以通过调用不带参数的bindtags来获取订单,然后通过使用包含订单的元组再次调用它来定义新订单:

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. 这样可确保在尝试读取选择之前执行文本选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM