Search code examples
tkinterttktkinter-textttkwidgetstkinter-label

Tkinter ttk update label style


I am trying to update the of the background color of a text label. For this I am using the ttk module of tkinter.

For some reason it doesn't want to execute the config.xx(style="xx.TLabel.

from tkinter import *
from tkinter import ttk

win = Tk()
win.geometry("1200x800") #1024*600
s = ttk.Style(win)

s.configure("CustomGrey.TLabel",   background="#4D4D4D", foreground="white")
s.configure("CustomGreen.TLabel",  background="#97D077", foreground="white")
s.configure("CustomYellow.TLabel", background="#FFD966", foreground="white")
s.configure("CustomRed.TLabel",    background="#FF6666", foreground="white")


s.configure("CustomRed.TLabel", background="#FF6666", foreground="white", font=('Time New Roman', 60), anchor= "c")


def updateLabelColor(color):
    if   color == "Green":  battery_lab.config(style="CustomGreen.TLabel")
    elif color == "Yellow": battery_lab.config(style="CustomYellow.TLabel")
    elif color == "Red":    battery_lab.config(style="CustomRed.TLabel")
 
updateLabelColor("Green")

The goal is that text can change color in a program. It does not matter if it is done via a tk or a ttk label.

Does anyone know what to do with this?


Solution

  • I'm not sure what you asked for. If you want to change a tkinter.Label's background color you can easily change it by adding background attribute:

    from tkinter import *
    root = Tk()
    label = Label(root, text="A Text", background="yellow")
    label.pack(pady=30, padx=50)
    root.mainloop()
    

    If you want to change a tkinter.Label's color by pressing a button or getting an input you can do this:

    from tkinter import *
    
    root = Tk()
    
    def update_Label_color(color):
        if color == "Green":
            label.config(background="green")
        elif color == "Yellow":
            label.config(background="yellow")
        elif color == "Red":
            label.config(background="red")
    
    color_variable = StringVar(value="Green")
    input = Entry(root, bg="orange", textvariable=color_variable)
    input.pack(pady=10, padx=50)
    button = Button(root, width=30, height=5, text="Button", command= lambda: update_Label_color(color_variable.get()))
    button.pack(pady=30, padx=50)
    label = Label(root, text="A Text", background="white")
    label.pack(pady=30, padx=50)
    
    root.mainloop()