Tkinter:基于关键字突出显示/颜色特定的文本行 [英] Tkinter: Highlight/Colour specific lines of text based on a keyword

查看:42
本文介绍了Tkinter:基于关键字突出显示/颜色特定的文本行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法来搜索一行文本,并在该行包含特定单词时突出显示该行.我有一个 tkinter 文本框,它有很多行,例如:

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 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!!

推荐答案

使用 文本搜索.

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()

这篇关于Tkinter:基于关键字突出显示/颜色特定的文本行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆