Search code examples
pythontkintercustomtkinter

Python - text color of one variable in multivariable sentence in Tkinter label


The text source consists out of elements from a nested lists. A label is created for each element in the list. Below the code:

list1 = [["test", 3, 2, 0], ["test2", 4, 1, 1],["test3", 0, 5, 2]]
row = 1
for i in list1:
    text = "name: {}, x: {}, y: {}, z: {}".format(i[0],i[1],i[2],i[3])
    customtkinter.CTkLabel(master=self.frame_1, text=text).grid(row=row, column=0, sticky='nw')
    row = row + 1

Now i want i[3] to have a color. The question is, how?


Solution

  • The easiest way to do this is to create multiple labels in a frame and set the colour of the one you want.

    list1 = [["test", 3, 2, 0], ["test2", 4, 1, 1],["test3", 0, 5, 2]]
    row = 1
    for i in list1:
        label_wrapper = customtkinter.CTkFrame(master = self.frame_1)
        label_wrapper.grid(row=row, column=0, sticky='nw')
        keys = ["name", "x", "y", "z"]
        for n, v in enumerate(i):
            text = "{}: {}".format(keys[n], v)
            label = customtkinter.CTkLabel(master=label_wrapper, text=text)
            if n == 3:
                label.configure(fg = "red")
            label.grid(row = 0, column = n)
        row = row + 1