Search code examples
pythontkintertextboxtkinter-entrycustomtkinter

Changing individual lines to different colors in a customtkinter textbox


I'd like to be able to change the color of text based on what the text contains in a CTkTextbox. I've been able to find something kind of similar in tkinter, "https://stackoverflow.com/questions/47591967/changing-the-colour-of-text-automatically-inserted-into-tkinter-widget", which does what I need but I am unable to get it to work in customkinter. I've tried tags, but it seems that regardless of the tag I specify when I insert the line it uses the last color defined in the tag config. Ignore the 0.0 in the insert, I actually want the last insert to be at the top of the list.

Any ideas?

import customtkinter

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        self.grid_rowconfigure(0, weight=1)  # configure grid system
        self.grid_columnconfigure(0, weight=1)

        self.textbox = customtkinter.CTkTextbox(master=self, width=400, corner_radius=0)
        self.textbox.grid(row=0, column=0, sticky="nsew")
        self.textbox.configure("1", text_color="red")
        self.textbox.configure("2", text_color="blue")

        self.textbox.insert("0.0", "Text color is red\n", "1")
        self.textbox.insert("0.0", "Text color is blue\n", "2")

app = App()
app.mainloop()


Solution

  • Note that .configure() is used to change options of the widget itself and it is not tag related.

    .tag_config() should be used on tag related options, but the options for a tkinter Text widget should be used instead of customtkinter options:

    # use .tag_config() instead of .configure()
    # and tkinter option "foreground" is used instead of customtkinter option "text_color"
    self.textbox.tag_config("1", foreground="red")
    self.textbox.tag_config("2", foreground="blue")
    

    Result:

    enter image description here