Ryan
Ryan

Reputation: 747

Tkinter Text Widget color certain text

I have a Text widget that is uneditable where text can be added with an Entry widget. I would like certain text in the Text widget to be differently colored than the rest depending on the type of text that is sent in. For example a possible output depending on types could be:

*Line one text* (color: Black)
*Line two text* (color: Blue)
*Line three text* (color: Black)

From what I have discovered it seems that this is possible to do using the tag_add and tag_configure method that the Text widget has but I am unsure how to do this.

I have the following method that appends the text to the Text widget and the ability to change the color of the text:

def append_to_display(self, text, color=standard):
    self.display.configure(state=NORMAL)
    self.display.tag_configure("color", foreground=color)
    self.display.insert(END, text + "\n", "color")
    self.display.configure(state=DISABLED)

However if I change the color to 'green' it doesn't change it for just the sent in text, it changes it for all the text.

So how do I make it work for only the text sent in?

Also note that I am running Python 3.6.1

Upvotes: 1

Views: 3079

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

You need to use a unique tag name for each color.

def append_to_display(self, text, color=standard):
    tag_name = "color-" + color
    self.display.tag_configure(tag_name, foreground=color)
    ...
    self.display.insert(END, text + "\n", tag_name)
    ...

Upvotes: 3

Related Questions