在 Python 2.7 中的 Tkinter 文本小部件中搜索单词列表

Searching for a list of words within a Tkinter text widgit in Python 2.7

我一直在尝试在我的 Tkinter GUI 上进行按钮检查,以在文本小部件中搜索特定单词的输入文本并使其显示为红色,我已经使用以下代码成功地做到了这一点:

list_of_words = ["foo", "bar`enter code here`"]
def check():
global counter
text.tag_remove('found', '1.0', END)
idx = '1.0'
x = 0
while True:
    idx = text.search(list_of_words[x], idx, nocase=1, stopindex=END)
    if not idx: break

    lastidx = '%s+%dc' % (idx, len(list_of_words[x]))
    text.tag_add('found', idx, lastidx)
    idx = lastidx
    text.tag_config('found', foreground='red')
    counter += 1
    print counter

但是我需要能够在输入中搜索 list_of_words 列表中的所有单词并将它们全部显示为红色。 有什么办法吗?

您的代码不会递增 x 因此,如果出现第一个单词,while 循环将永远不会终止。但是,它确实会无缘无故地增加全局变量 counter

为什么不使用 for 循环简单地遍历目标词列表?内部 while 循环将在文本小部件中搜索每个单词的所有实例,并标记它们以突出显示。 while 循环的终止条件是在小部件中找不到当前单词。然后,在所有单词都被标记之后,设置它们的颜色。

def check():
    text.tag_remove('found', '1.0', END)

    for word in list_of_words:
        idx = '1.0'
        while idx:
            idx = text.search(word, idx, nocase=1, stopindex=END)
            if idx:
                lastidx = '%s+%dc' % (idx, len(word))
                text.tag_add('found', idx, lastidx)
                idx = lastidx

    text.tag_config('found', foreground='red')