【问题标题】:Highlighting words and then unhighlighting using tkinter突出显示单词,然后使用 tkinter 取消突出显示
【发布时间】:2017-11-16 21:22:31
【问题描述】:

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

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")

但这没有运气。

【问题讨论】:

  • 请展示您实际尝试过的内容,而不仅仅是对某些代码的解释。另外,如果你没试过,用tag_remove去掉“highlight”标签。
  • @BryanOakley 我已经添加了您要求的详细信息:)

标签: python tkinter


【解决方案1】:

您可以使用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()

【讨论】:

  • 救命!谢谢你:)