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")
txt.insert(0.0,line)
else:
txt.insert(0.0,line)
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.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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With