heliosk
heliosk

Reputation: 1161

Python tkinter - change Label font color dynamically

I have a Label that show the status of my db connection. I need to update the text of this Label whenever something happens, but also I want to change the color of this label. I'm using update_idletasks() method, but it just change the text not the color.

    self.dtbase_value = StringVar()
    self.dtbase_color = StringVar()
    self.dtbase_bg    = StringVar()

    self.dtbaselbl = Label(self.right_frame, textvariable = self.dtbase_value, fg = self.dtbase_color.get(), bg = self.dtbase_bg.get()).pack(side=TOP)

This is the part that I call the update.

    self.dtbase_value.set(self.get_current_time() + ': connection established')
    self.dtbase_color.set('SpringGreen')
    root.update_idletasks()

Is there any specific method to dinamically update the attributes of a Label component?

Upvotes: 1

Views: 15996

Answers (1)

Kevin
Kevin

Reputation: 76194

First, you need to get a reference to the Label object. You might be thinking "I already have one, it's self.dtbaselbl". But that value is actually None. You're assigning the result of Label().pack() to it, and pack always returns None. See Why do my Tkinter widgets get stored as None? for more information.

Pack and assign on separate lines:

self.dtbaselbl = Label(self.right_frame, textvariable = self.dtbase_value)
self.dtbaselbl.pack(side=TOP)

Now that you have a proper reference, you can set the label's configuration options, including color, at any time using the .config method.

self.dtbase_value.set(self.get_current_time() + ': connection established')
self.dtbaselbl.config(fg="SpringGreen")
root.update_idletasks()

Upvotes: 4

Related Questions