gpt4 book ai didi

python - 使用 tkinter 突出显示单词然后取消突出显示

转载 作者:行者123 更新时间:2023-12-01 02:26:27 25 4
gpt4 key购买 nike

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

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_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()

关于python - 使用 tkinter 突出显示单词然后取消突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47339287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com