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

Time:07-19

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?

CodePudding user response:

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 = root)
    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

root.mainloop()

CodePudding user response:

You can use add tag method to add a tag to a part of the text and then change its properties like color or even background color. let's say you want to color numbers through 3-6:

text = "0123456789"
text.tag_add("name of the tag","1.3","1.7") 

here the 1.3 refers to two values the 1 is for the first line, and the number after the dot to the index[] of the text, now 3 so "3", and the last argument is excluded so you need index[7] one more... and the whole area from 1.3 til 1.7 will have its color changed.

text.tag_config("name of the tag",foreground="color")

that's it

-Sam

  • Related