python - Tkinter:根据关键字突出显示/着色特定的文本行

标签 python python-2.7 python-3.x tkinter

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

相关文章:

Python 打开和关闭文件 - 不直观

mysql - 更新 MySQL 报告受影响的行过多的 Python 脚本

python - Python中的 `await`是否会屈服于事件循环?

python - 应用 django/docker 文件中的更改

python - 如何使用pylab远程保存图形?

python - 字典的平均值

python - 在 Python 中计算抵押贷款利息

python - 如何用 BeautifulSoup 抓取页面?页面源不匹配检查元素

python-2.7 - 使用 random.choice 列出索引超出范围错误

尝试在远程桌面上运行应用程序时出现 Python 错误