luroc luroc - 5 months ago 52
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)
self.slogan.pack()

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

root = Tk()
app = App(root)
root.mainloop()


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.

Answer

Here's your issue:

time.sleep(1)

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.configure(bg='red')
    self.slogan.after(1000, # milliseconds
                      self.change_back)

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

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.

Comments