我正在寻找一种简单的方法来搜索一行文本并突出显示包含特定单词的行。我有一个 tkinter 文本框,其中有很多行,例如:
“等等等等失败了等等”
“blah blah blah 通过了 blah blah”
我想将“失败”行的背景颜色设置为红色。到目前为止我有:
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)
这打印出了我想要的一切,但对颜色没有任何影响
这显然是更改文本颜色的错误方法。请帮忙!!
最佳答案
使用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()
关于python - Tkinter:根据关键字突出显示/着色特定的文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17829713/