Tkinter 动态更改文本框中重复字符串的文本颜色 [英] Tkinter dynamically changing text colour of recurring strings in a textbox
问题描述
我设置了一个 Tkinter 文本框来显示文件的内容.示例行如下:
I have a Tkinter textbox set to display the contents of a file. An example line from which would be as follows:
SUCCESS - Downloaded example.jpg
File was 13KB in size
我想要做的是将包含成功"一词的任何行的文本颜色更改为蓝色.请注意,我需要这个是动态的,因为这个词可以在一个文件中找到数百次,并且无法预测它会在哪里.这是我用来将文件内容输出到文本框的代码.哪个工作正常.
What I want to do is have any line containing the word "SUCCESS" have it's text colour changed to blue. Please note that I need this to be dynamic since this word could be found hundreds of times in the one file and there's no way of predicting where it will be. This is the code I am using to output the file contents to the text box. Which works fine.
log = open(logFile, 'r')
while 1:
line = log.readline()
if len(line) == 0:
break
else:
self.txtLog.insert(Tkinter.END, line)
self.txtLog.insert(Tkinter.END, os.linesep)
log.close()
我正在尝试像下面的示例行一样使用 tag_add 和 tag_config,但无济于事.
I'm trying to use tag_add and tag_config like the example lines below but to no avail.
`self.txtLog.tag_add("success", "1.0", "1.8")
self.txtLog.tag_config("success", foreground="blue")`
`
推荐答案
您需要配置一个标签,并在添加文本时指定该标签.这应该有效(虽然没有经过测试):
You need to config a tag, and specify that tag when adding the text to the end. This should work (although not tested):
self.txtLog.tag_config("success", foreground="blue", font="Arial 10 italic")
log = open(logFile, 'r')
while 1:
line = log.readline()
if len(line) == 0:
break
else:
tags = ("success",) if line.startswith("SUCCESS") else None
self.txtLog.insert(Tkinter.END, line+os.linesep, tags)
log.close()
另外,我刚刚注意到你在 tag_config
之前使用了 tag_add
,我认为它应该是相反的.
Also, I just noticed that you are using tag_add
before tag_config
, I believe it should be the opposite for it to work.
这篇关于Tkinter 动态更改文本框中重复字符串的文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!