Python 有没有一种方法可以使。在tkinter中搜索而不是在单词中查找单词?

Python 有没有一种方法可以使。在tkinter中搜索而不是在单词中查找单词?,python,tkinter,Python,Tkinter,我正在构建一个程序,在用户编写文本小部件时突出显示文本小部件中的某些单词 到目前为止,一切都在运行,只是程序一直在单词中突出显示单词,我不知道如何让它不这样做 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=

我正在构建一个程序,在用户编写文本小部件时突出显示文本小部件中的某些单词

到目前为止,一切都在运行,只是程序一直在单词中突出显示单词,我不知道如何让它不这样做

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()
从tkinter导入*
root=Tk()
帧=帧(根)
frame.grid(行=0,列=0,sticky=“nsew”)
root.grid_rowconfigure(0,权重=1)
root.grid\u columnconfigure(0,权重=1)
文本框=文本(框架,宽度=100,高度=10)
textbox.grid(行=1,列=7,列span=10)
textbox.tag_config(“蔬菜”,前景为绿色”)
textbox.tag_config(“水果”,前景为红色”)
def搜索(文本框、关键字、标记):
位置='1.0'
尽管如此:
idx=textbox.search(关键字、位置、结束、nocase=True)
如果不是idx:
打破
pos='{}+{}c'.格式(idx,len(关键字))
textbox.tag\u add(标签、idx、pos)
def搜索2(事件):
蔬菜中的单词:
搜索(文本框,单词,“蔬菜”)
水果中的单词:
搜索(文本框、命令集、“水果”)
textbox.bind(“,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)

添加
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)

使用
\y
匹配单词边界。请参阅使用
\y
匹配单词边界。请参阅您是否确实尝试过此方法?这行不通。默认情况下,文本小部件
search
方法不使用正则表达式。我了解到它确实有效。需要
regexp=True
选项。您确实尝试过这个吗?这行不通。默认情况下,文本小部件
search
方法不使用正则表达式。我了解到它确实有效。需要
regexp=True
选项。