【问题标题】:Searching for a list of words within a Tkinter text widgit in Python 2.7在 Python 2.7 中搜索 Tkinter 文本小部件中的单词列表
【发布时间】:2015-06-01 16:18:08
【问题描述】:

我一直在尝试在我的 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 列表中的所有单词并将它们全部显示为红色。 有没有办法做到这一点?

【问题讨论】:

    标签: python list python-2.7 tkinter


    【解决方案1】:

    您的代码不会增加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')
    

    【讨论】:

    • 效果很好,我明白了我现在所做的,我实际上并没有在列表中移动,因此只能检查一个字。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    相关资源
    最近更新 更多