luroc luroc - 4 months ago 28
Python Question

how to continuously change background color in tkinter

Python beginner here.

I need a way to display a sequence of colors in Python and I chose to do that with Tkinter.

I managed to have a Button and make it change it's background color when clicked, but when I do multiple changes, only the last one is rendered.

I'm almost sure that it's not a problem of Tkinter itself, but of the way Python itself handles functions so this probably got already discussed here, but as a beginner I really don't know what to look for. The right keyword would be enough I guess.

from Tkinter import *
import time
class App:
def __init__(self, master):
self.slogan = Button(command=self.change)

def change(self):
self.slogan.configure(bg = 'red')
self.slogan.configure(bg = 'blue')

root = Tk()
app = App(root)

This code is supposed to on click change the color to red, wait and change the color to blue, instead it only changes the color to blue.


Here's your issue:


Never sleep in a GUI program. It stops the mainloop from doing anything (i.e. updating your graphics). It will freeze the gui, giving you no responses for a second as well.

Instead, separate it into two callbacks, and have the first schedule the other with an after- i.e.:

def change(self):
    self.slogan.after(1000, # milliseconds

def change_back(self):

Also, your App should probably pass the master to the button (Button(master, command=self.change)) and/or should be subclassed from Tkinter.Frame and then have the button packed inside it.