突出显示单词然后使用tkinter取消强调

时间:2017-11-16 21:22:31

标签: python tkinter

我有一个程序会突出显示文本框中的单词,但是,我希望能够实现的是当再次单击相同的单词时,该单词将不会突出显示。这可能吗?下面是单击单词时执行操作的代码部分。我希望你能帮忙。

def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap="none")
        self.text.pack(fill="both", expand=True)

        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="green", foreground="black")

        with open(__file__, "rU") as f:
            data = f.read()
            self.text.insert("1.0", data)

def _on_click(self, event):
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")

我尝试使用:

def _on_click(self, event):
    self.text.tag_remove("highlight", "1.0", "end")
    self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    if self.text.tag_names == ('sel', 'highlight'):
        self.text.tag_add("highlight", "insert wordstart", "insert wordend")
    else:
        self.text.tag_remove("highlight", "1.0", "end")

但是没有运气。

1 个答案:

答案 0 :(得分:2)

您可以使用tag_names获取特定索引处的标记列表。然后,只需要调用tag_addtag_remove,具体取决于标记是否出现在当前单词上。

示例:

import tkinter as tk

class Example(object):
    def __init__(self):
        self.root = tk.Tk()
        self.text = tk.Text(self.root)
        self.text.pack(side="top", fill="both", expand=True)
        self.text.bind("<ButtonRelease-1>", self._on_click)
        self.text.tag_configure("highlight", background="bisque")

        with open(__file__, "r") as f:
            self.text.insert("1.0", f.read())

    def start(self):
        self.root.mainloop()

    def _on_click(self, event):
        tags = self.text.tag_names("insert wordstart")
        if "highlight" in tags:
            self.text.tag_remove("highlight", "insert wordstart", "insert wordend")
        else:
            self.text.tag_add("highlight", "insert wordstart", "insert wordend")

if __name__ == "__main__":    
    Example().start()