DCA- DCA- - 8 months ago 45
Python Question

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 blah Failed blah blah"

"blah blah blah Passed blah blah"

and I would like to set the background colour of the "Failed" line to be red. so far I have:

for line in results_text:
if "Failed" in line:
txt.tag_config("Failed", bg="red")

this prints out what everything I want but does nothing to the colours

this clearly is the wrong way to change the text colour. Please help!!


Use Text.search.

from Tkinter import *

root = Tk()
t = Text(root)
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:
        pos = '{}+{}c'.format(idx, len(keyword))
        text_widget.tag_add(tag, idx, pos)

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