[英]Is there a way to make .search in tkinter not find words within words?
我正在構建一個程序,該程序在用戶編寫文本小部件時突出顯示某些單詞。
到目前為止,所有程序都可以正常工作,只不過該程序一直在單詞中突出顯示單詞,而且我不知道如何使其不這樣做。
from tkinter import *
root = Tk()
frame = Frame(root)
frame.grid(row=0, column=0, sticky="nsew")
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
textbox = Text(frame,width=100, height=10)
textbox.grid(row=1, column=7, columnspan=10)
textbox.tag_config("vegetables", foreground='green')
textbox.tag_config("fruits", foreground='red')
def search(textbox, keyword, tag):
pos = '1.0'
while True:
idx = textbox.search(keyword, pos, END, nocase=True)
if not idx:
break
pos = '{}+{}c'.format(idx, len(keyword))
textbox.tag_add(tag, idx, pos)
def search2(event):
for word in vegetables:
search(textbox, word, "vegetables")
for word in fruits:
search(textbox, ordet, "fruits")
textbox.bind("<space>", search2)
frame.mainloop()
我在這里使用“蔬菜”和“水果”作為示例,以使程序的功能更直觀。
我要解決的問題可以通過以下句子來說明,該句子說明了程序如何在另一個單詞中識別出蔬菜,這意味着其他含義:
“我想要的只是地球上的豌豆 ”
任何幫助表示贊賞!
添加regexp=True
選項,並使用\\y
匹配單詞邊界。
def search(textbox, keyword, tag):
pos = '1.0'
while True:
idx = textbox.search(fr'\y{keyword}\y', pos, END, nocase=True, regexp=True)
if not idx:
break
pos = '{}+{}c'.format(idx, len(keyword))
textbox.tag_add(tag, idx, pos)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.