Search on blog:

Python: How to change color in Text using tags

Widget Text has function insert() to insert text and it has option tags to assing tag (or many tags) to inserted text. This tag can be used to change color (background, foreground) and font and other properties.

import tkinter as tk

root = tk.Tk()

txt = tk.Text(root)
txt.pack()

txt.tag_config('warning', background="yellow", foreground="red")

txt.insert('end', "Hello\n")
txt.insert('end', "Alert #1\n", 'warning')
txt.insert('end', "World\n")
txt.insert('end', "Alert #2\n", 'warning')

root.mainloop()
text

If assign different color to tag then all elements with this tag change color too.

import tkinter as tk

# --- functions ---

def on_click():
    txt.tag_config('warning', background="green", foreground="red")
    print(txt.tag_config('warning'))

# --- main ---

root = tk.Tk()

txt = tk.Text(root)
txt.pack()

txt.tag_config('warning', background="yellow", foreground="red")

txt.insert('end', "Hello\n")
txt.insert('end', "Alert #1\n", 'warning')
txt.insert('end', "World\n")
txt.insert('end', "Alert #2\n", 'warning')

button = tk.Button(root, text='Change', command=on_click)
button.pack()

root.mainloop()

If you use after() to change color in tag then you can get blinking text.

import tkinter as tk

# --- functions ---

def set_green():
    txt.tag_config('warning', background="green", foreground="red")
    root.after(500, set_yellow)

def set_yellow():
    txt.tag_config('warning', background="yellow", foreground="red")
    root.after(500, set_green)

# --- main ---

root = tk.Tk()

txt = tk.Text(root)
txt.pack()

txt.tag_config('warning', background="yellow", foreground="red")

txt.insert('end', "Hello\n")
txt.insert('end', "Alert #1\n", 'warning')
txt.insert('end', "World\n")
txt.insert('end', "Alert #2\n", 'warning')

root.after(500, set_green)

root.mainloop()

If you like it
Buy a Coffee