更新时间:2023-02-01 17:03:09
您可以使用 tag_names
来获取某个索引处的标签列表.然后只需调用 tag_add
或 tag_remove
取决于当前单词上是否存在标签.
You can use tag_names
to get a list of tags at a certain index. Then it's just a matter of calling tag_add
or tag_remove
depending on whether the tag is present on the current word or not.
示例:
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()