sampi
sampi

Reputation: 3

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

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

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?

Upvotes: 0

Views: 1179

Answers (1)

mhawke
mhawke

Reputation: 87134

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.

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

Upvotes: 2

Related Questions