Search code examples
tkinterglobal-variablespython-3.8

Changing tkinter bg from a function


Trying to change background color when a condition is met, but can't get it to work bg stays red.

import tkinter as tk

bg_color = '#7C2D32' # bg red
x=2

def test(): 
    test_label['text'] = 1234
    y=1
    if x>y:
        global bg_color
        bg_color = '#235C32' # bg green
    root.after(5000,test)

root = tk.Tk()

test_label=tk.Label(root,font='helvetica 30',bg=bg_color,fg='#f4f4f4')
test_label.grid(row=0,column=0)

test()
root.mainloop()

Solution

  • You can't just change a string variable and expect the widget to change. You must explicitly call the configure method of the widget.

    test_label.configure(bg=bg_color)