0

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?

Burger King
  • 2,945
  • 3
  • 20
  • 45
sampi
  • 3
  • 2

1 Answers1

2

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')
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • That works beautifully, I see what I did now, I wasn't actually moving up the list at all and therefore couldn't check more than one word. Thank you! – sampi Mar 28 '15 at 11:25