1

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?

heliosk
  • 1,113
  • 3
  • 23
  • 45
  • i **think** you need to remove the brackets here `fg = self.dtbase_color.get(), bg = self.dtbase_bg.get()` – Nullman Jun 01 '17 at 13:26
  • I think you want to [`trace`](http://effbot.org/tkinterbook/variable.htm) changes and call a callback function to change appearence of you Label (which is `None` right now). – CommonSense Jun 01 '17 at 13:29

1 Answers1

4

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()
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • thanks Kevin. It worked. I was trying to use `.config`, but it didn't work until i made the pack adjust. – heliosk Jun 01 '17 at 13:33