Dynamically change widget background color in Tkinter

from my first impression I think this should be what you're looking for, as a simple example

from Tkinter import *

root = Tk()
global colour
global colourselection 
global count 
colour = ""
colourselection= ['red', 'blue']
count = 1

def start(parent):
    Tk.after(parent, 1000, change)

def change():
    global colour 
    global colourselection
    global count 
    if (count < 2 ):
        colour = colourselection[count]
        button.configure(bg = colour)
        count + 1
    else:
        colour = colourselection[count]
        button.configure(bg = colour)
        count = 1 
    start(root)



button = Button(text = 'start', command = lambda: start(root))
button.pack()

root.mainloop()

I'm sure you can work out any issues, it's not been tested


The background colors will not automatically change. Tkinter has the ability to do such a thing with fonts but not with colors.

You will have to write some code to iterate over all of the widgets and change their background colors.


(I posted this answer to a similar question, I think this will do it for this case too:)

For the life of me, I couldn't get it to work just using the configure method. What finally worked was setting the desired color (in my case, of a button) to a StringVar() (directly to the get()), and then using the config on the button too.

I wrote a very general example for the use case I need the most (which is a lot of buttons, where I need references to them (tested in Python 2 and 3):

Python 3:

import tkinter as tk

Python 2:

import Tkinter as tk

Code

root = tk.Tk()
parent = tk.Frame(root)

buttonNames = ['numberOne','numberTwo','happyButton']
buttonDic = {}
buttonColors = {}

def change_color(name):
    buttonColors[name].set("red")
    buttonDic[name].config(background=buttonColors[name].get())

for name in buttonNames:
    buttonColors[name] = tk.StringVar()
    buttonColors[name].set("blue")
    buttonDic[name] = tk.Button(
            parent,
            text = name,
            width = 20,
            background = buttonColors[name].get(),
            command= lambda passName=name: change_color(passName)
            )

parent.grid(row=0,column=0)
for i,name in enumerate(buttonNames):
    buttonDic[name].grid(row=i,column=0)

root.mainloop()

Tags:

Python

Tkinter