Tkinter: Jak zmienić kolor w Text używając tagów
Widget Text ma funkcję insert() do wstawiania tekstów i ona ma opcję tags do przypisywania tagu (lub wiele tagów) do wstawianego tekstu. Ten tag może być użyty do zmiany koloru (background, foreground) oraz czcionki oraz innych właściwości.
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()

Jeśli się przypisze inny kolor do tagu wtedy wszystkie elementy z tym tagiem zmienią kolor też.
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()
Jeśli się użyje after() do zmieniania koloru w tagu to wtedy można otrzymać mrugający tekst.
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()
Notatki:
Stackoverflow: Changing the colour of text automatically inserted into tkinter widget
If you like it
Buy a Coffee
