Hi all,
I am trying to update the colour of a Tkinter label, so as the value of a variable changes so to does the colour of the text.
Below is a simple example of what I am trying to achieve, but the problem is when I press the button I want the labels colour to update to red.

from Tkinter  import *
root = Tk()
colour = StringVar()
colour.set('blue')
def colourUpdate():
    colour.set('red')
    root.update()
    
btn = Button(root, text = "Click Me", command = colourUpdate)
l = Label(root, textvariable=colour, fg = colour.get())
l.pack()

btn.pack()
root.mainloop()

Dani AI

Generated

textvariable only updates the label’s text; it does not bind other options like fg. Instead of calling root.update() (which is rarely needed and can cause re-entrancy issues), tie the StringVar to the label’s color with a variable trace so the UI updates automatically when the variable changes.

from Tkinter import Tk, StringVar, Label, Button

root = Tk()
color = StringVar(value='blue')

lbl = Label(root, textvariable=color)
lbl.pack()

def on_color_change(*_):
    lbl.configure(fg=color.get())  # keep color in sync with the variable

color.trace('w', on_color_change)  # Python 2
Button(root, text='Set red', command=lambda: color.set('red')).pack()

root.mainloop()

Notes:

  • In Python 3, import tkinter, and use trace_add('write', callback) instead of trace. See tkinter variables and traces.
  • For periodic or delayed updates, prefer widget.after(ms, func) over update(); see after.
  • If you switch to ttk.Label, the foreground is controlled by a style (e.g., Style().configure('My.TLabel', foreground='red')) rather than fg. The classic Label options are documented in the Tk man page: label options.

Recommended Answers

All 2 Replies

The label's fg option is not executed when root.update is called. It does not seem logical.
You should set the fg option of the label in the command somehow. I am not an expert int tkinter, but recreating it is always a possibility.
Textvariable applies only for the text option. As far as I read the docs.

def colourUpdate():
    l.config(fg='red')
    root.update()

Like this?

from Tkinter  import *
def colourUpdate():
    colour.set('red' if colour.get()!='red' else 'blue')
    print colour.get()
    l.configure(fg=colour.get())

root = Tk()
colour = StringVar()
colour.set('red')
    
btn = Button(root, text = "Click Me", command = colourUpdate)
l = Label(root, textvariable=colour, fg = colour.get())
l.pack()

btn.pack()
root.mainloop()

l is not the most recommendable variable name.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.