Change tkinter label color multiple times in same function

50 Views Asked by At

I want to change the color of a label twice in the same function. I can't seem to get that to work.

The function is something like

    def do_work():
        print("in progress")
        label.config(font=("Calibri", 1, "bold"), fg="white")
        # run calculations
        print("complete")
        label.config(font=("Calibri", 1, "bold"), fg="green")

It seems like tkinter only allows one of these labels to work. It feels like I'm missing something fundamental about how tkinter works. Thank you.

2

There are 2 best solutions below

1
On

Here is sample code how you can change the color of the Label (after one second):

import tkinter as tk


def on_button_click():
    label.config(font=("Calibri", 12, "bold"), fg="white")
    # after 1 second, it becomes green
    window.after(1000, lambda: label.config(font=("Calibri", 12, "bold"), fg="green"))


window = tk.Tk()
window.title("Tkinter Button Example")
button = tk.Button(window, text="Click Me", command=on_button_click)
label = tk.Label(window, text="Sample Text In Label")
label.config(font=("Calibri", 12, "bold"), fg="yellow")

button.pack(pady=10)
label.pack(pady=10)

window.mainloop()

Creates this application (clicking changes the first yellow text to white then after one second to green):

enter image description here

0
On

root.update() forces the config change. Otherwise tkinter waits until the next event loop iteration to update config. When you change the configuration of a Tkinter widget, the change does not happen immediately. Instead, the change is queued up and executed when the next event loop iteration occurs. This can be a problem if you need to make changes to the widget's configuration in response to user input.