突出显示单词,然后使用tkin取消突出显示

2024-04-25 01:07:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,将突出显示文本框中的一个字,然而,我想能够实现的是,当同一个字被再次点击,然后这个字将被取消高亮显示。这可能吗?下面是一段代码,当一个单词被点击时,它会做一些事情。我希望你能帮忙。你知道吗

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

但那没有运气。你知道吗


Tags: textselfadddatainitondeftag
1条回答
网友
1楼 · 发布于 2024-04-25 01:07:48

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

相关问题 更多 >