如何解决Tkinter检查字母/单词是否被删除并突出显示替换的字母/单词
因此,我有一个小程序,您可以在其中找到一个字符串并将其突出显示,例如,在文本字段中您有一个单词:“ ghazi”,在我写“ g”的查找字段中,现在它将突出显示文本字段中的“ g”,但是如果我从查找字段中删除“ g”并将其替换为“ h”,则会突出显示“ gh”,我想要的是find方法仅突出显示字母“ h”,因为“ g” “将从输入框中删除(查找字段)。 我试图检查输入字段是否为空,以便我可以删除突出显示但它没有用,这是代码:
def Find(self):
count=IntVar()
s=self.text.search(self.entry.get(),'1.0',stopindex=END,count=count)
self.text.tag_configure("match",background='yellow')
end=f'{s}+{count.get()}c'
self.text.tag_add("match",s,end)
self.text.bind("<Button-1>",lambda event_data: self.text.tag_remove("match","1.0",END))
if self.entry.get()==" ":
self.text.tag_remove("match",END)
其中self.text
是指Text()小部件对象。
解决方法
两个字母都突出显示的原因是,您没有从“ g”中删除“ match”标签,而只是将其添加到“ h”中。因此,如果您未单击文本小部件,则突出显示将停留在“ g”上。因此,您的Find()
函数应以self.text.tag_remove("match","1.0",END)
开头。
您还可以在代码中改进其他方面:
-
我将检查条目是否为空,如果是,则不执行搜索:
if not self.entry.get().strip(): return # ... do the search
-
无需在每次运行
Find()
时配置“匹配”标签,只需在创建self.text
时配置一次。 -
与绑定到
的内容相同<Button-1>
这是一个完整的例子:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
count = tk.IntVar(root)
entry = ttk.Entry(root)
text = tk.Text(root)
text.tag_configure('match',background='yellow')
text.bind("<Button-1>",lambda event_data: text.tag_remove("match",tk.END))
def find():
text.tag_remove("match",tk.END) # clear highlights
string = entry.get()
if not string.strip(): # entry contains only spaces:
return
s = text.search(string,'1.0',stopindex=tk.END,count=count)
end = f'{s}+{count.get()}c'
text.tag_add("match",s,end)
button = ttk.Button(root,text='Find',command=find)
text.pack()
entry.pack()
button.pack()
root.mainloop()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。