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)开头。

您还可以在代码中改进其他方面:

  1. 我将检查条目是否为空,如果是,则不执行搜索:

    if not self.entry.get().strip():
        return
    # ... do the search
    
  2. 无需在每次运行Find()时配置“匹配”标签,只需在创建self.text时配置一次。

  3. 与绑定到<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()