Tkinter 检查 letter/word 是否被删除并突出显示替换的 letter/word

Tkinter check if a letter/word is getting deleted and highlight the replaced letter/word

所以,我有一个小程序,您可以在其中找到一个字符串并将其突出显示,例如,您在文本字段中有单词:“ghazi”,在查找字段中我写了“g”,现在它将在文本字段中突出显示“g”,但是如果我从查找字段中删除“g”并将其替换为“h”,它会突出显示“gh”我想要的是查找方法只突出显示字母“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","1.0",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()都配置“match”标签,创建self.text.[=17=时只需配置一次即可]

  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", "1.0", tk.END))

def find():
    text.tag_remove("match", "1.0", 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()