This is my code:
import tkinter as tk
def add_text(message, color='black'):
text_box.config(state=tk.NORMAL, fg=color)
text_box.insert(tk.END, message + "\n")
text_box.config(state=tk.DISABLED)
root = tk.Tk()
text_box = tk.Text(state=tk.DISABLED, font=("Arial 18", 16))
text_box.grid(row=0, column=0, sticky="nsew")
add_text("word")
add_text("word_with_color", 'red')
add_text("word")
tk.mainloop()
I only want the "word_with_color"
string to be in other color how do I do that?
The function I tried changes the whole text and thats not what I want.
To add color or other attributes to a range of text you first configure a tag to have the attributes that you want and then add the tag to the range of text you want to affect. You can either add the tag when you add the text with insert
, or add it some time later with the tag_add
method.
First, configure a tag to have a color. The tag name can be anything you want.
text_box.tag_configure("warning", foreground="red")
Next, you can add the tag when you call insert
. When you call insert
you can supply a list of tags after text. You can then add additional text and tags after that.
In the following example, the tag is added to the text but not the newline.
def add_text(message, tags=None):
text_box.config(state=tk.NORMAL)
text_box.insert(tk.END, message, tags, "\n")
text_box.config(state=tk.DISABLED)
You can call it like this:
add_text("word")
add_text("word_with_color", "warning")
add_text("word")