Joe
Joe

Reputation: 895

Tkinter dynamically changing text colour of recurring strings in a textbox

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

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")`

`

Upvotes: 3

Views: 3477

Answers (1)

jadkik94
jadkik94

Reputation: 7068

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

Also, I just noticed that you are using tag_add before tag_config, I believe it should be the opposite for it to work.

Upvotes: 3

Related Questions