在Python2.7中搜索Tkinter文本widgit中的单词列表

在Python2.7中搜索Tkinter文本widgit中的单词列表,python,list,python-2.7,tkinter,Python,List,Python 2.7,Tkinter,我一直在尝试在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_w

我一直在尝试在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
但是,我需要能够搜索输入中的所有单词,并将它们全部显示为红色。
有没有办法做到这一点

您的代码不会递增
x
,因此,如果出现第一个单词,while循环将永远不会终止。但是,它会在没有明显原因的情况下增加全局变量
计数器

为什么不简单地用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')

这很好,我知道我现在做了什么,我根本没有在列表中上移,因此只能检查一个单词。非常感谢。