1

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

Ryan
  • 727
  • 2
  • 14
  • 31
  • Possible duplicate of [How to change the color of certain words in the tkinter text widget?](http://stackoverflow.com/questions/14786507/how-to-change-the-color-of-certain-words-in-the-tkinter-text-widget) – J. Piquard Mar 23 '17 at 06:05

1 Answers1

3

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)
    ...
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685