DCA*_*CA- 3 python tkinter python-2.7 python-3.x
我正在寻找一种简单的方法来搜索文本行,如果它包含特定的单词则突出显示该行.我有一个tkinter文本框,有很多行,如:
"等等等等等等等等"
"等等等等等等等等等等"
我想将"失败"行的背景颜色设置为红色.到目前为止我有:
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)
Run Code Online (Sandbox Code Playgroud)
这打印出我想要的一切,但对颜色没有任何作用
这显然是改变文字颜色的错误方法.请帮忙!!
使用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()
Run Code Online (Sandbox Code Playgroud)