3

我正在寻找一种简单的方法来搜索一行文本并在该行包含特定单词时突出显示该行。我有一个 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)

这打印出我想要的一切,但对颜色没有任何作用

这显然是更改文本颜色的错误方法。请帮忙!!

4

1 回答 1

6

使用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()
于 2013-07-24T09:36:20.153 回答