Skip to content Skip to sidebar Skip to footer

Tkinter: Highlight/colour Specific Lines Of Text Based On A Keyword

I looking for a simple way to search through a line of text and highlight the line if it contains a specific word. I have a tkinter text box that has lots of lines like: 'blah blah

Solution 1:

Use Text.search.

from Tkinter import *

root = Tk()
t = Text(root)
t.pack()
t.insert(END, '''\
blah blah blah Failed blah blah
blah blah blah Passed blah blah
blah blah blah Failed blah blah
blah blah blah Failed blah blah
''')
t.tag_config('failed', background='red')
t.tag_config('passed', background='blue')

def search(text_widget, keyword, tag):
    pos = '1.0'
    while True:
        idx = text_widget.search(keyword, pos, END)
        if not idx:
            break
        pos = '{}+{}c'.format(idx, len(keyword))
        text_widget.tag_add(tag, idx, pos)

search(t, 'Failed', 'failed')
search(t, 'Passed', 'passed')

#t.tag_delete('failed')
#t.tag_delete('passed')

root.mainloop()

Post a Comment for "Tkinter: Highlight/colour Specific Lines Of Text Based On A Keyword"