在Python 2.7中的Tkinter文本widgit中搜索单词列表 [英] Searching for a list of words within a Tkinter text widgit in Python 2.7

查看:142
本文介绍了在Python 2.7中的Tkinter文本widgit中搜索单词列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to get a button check on my Tkinter GUI to search entered text into a text widget for a specific word and make it appear red, I've managed to do that using the following code:

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列表中的所有单词,并将它们全部显示为红色. 有什么办法吗?

However I need to be able to search the input for all words on the list_of_words list and display them all red. Is there any way of doing this?

推荐答案

您的代码不会递增x,因此,如果出现第一个单词,则while循环将永远不会终止.但是,它没有明显的原因会增加全局变量counter.

Your code does not increment x so, if the first word is present, the while loop will never terminate. It does, however, increment global variable counter for no apparent reason.

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

Why not simply iterate over the list of target words with a for loop? An inner while loop will search the text widget for all instances of each word, tagging them for highlighting. The termination condition for the while loop is that the current word was not found in the widget. Then, after all words have been tagged, set their colour.

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')

这篇关于在Python 2.7中的Tkinter文本widgit中搜索单词列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆