【问题标题】:Tkinter: Highlight/Colour specific lines of text based on a keywordTkinter:根据关键字突出显示/着色特定的文本行
【发布时间】:2013-07-23 16:12:24
【问题描述】:

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

这会打印出我想要的所有东西,但对颜色没有任何作用

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 2013-04-07
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多