Farhan Choudhary
Farhan Choudhary

Reputation: 13

How do I constantly change the background the colour?

I am working on a Loop, with Tkinter and was wondering how I could change to code so that I could change the background every second. In this code should work but whenever I run the program it crashes!

I have gotten a professional to look at it but still, we were not able to figure out why this code wasn't working. Also when you get rid of the while True: part it only configures the background to the last color.

from Tkinter import *
import time

root = Tk()

root.geometry("500x500+200+200")
root.title("Epilepsy Giver")
root.resizable(width = FALSE, height = FALSE)

def wait():
    time.sleep(1)

def start():
    while True:
        wait()
        root.configure(background='red')
        wait()
        root.configure(background='orange')
        wait()
        root.configure(background='yellow')
        wait()
        root.configure(background='green')
        wait()
        root.configure(background='blue')
        wait()
        root.configure(background='purple')
        wait()
        root.configure(background='violet')

startButton = Button(root,text="START",command=start)
startButton.pack()

root.mainloop()

Upvotes: 1

Views: 1163

Answers (3)

Anddrrw
Anddrrw

Reputation: 80

To futher clarify abccd's answer, the issue with your code lies in using time.sleep() vs Tk's after().

In your example, sleep() will freeze the program execution. Tk doesn't have time to redraw the window between the calls to to sleep, so you're effectively seeing an infinite loop of sleep() commands. Hence the freezing/crashing.

after(), on the other hand will schedule your Tk application the way you need it to.

Upvotes: 0

RandomB
RandomB

Reputation: 3749

Early, to avoid strange errors with Tk I created all UI elements in one thread and start there loop which waits for incoming events. All interactive elements or activity from other threads puts "queries"/event to this queue, but real changing of elments happens in the thread where element was created. This was rule for Tcl/Tk (8.5, 8.6). Try such model. Please, see how it's done in this code - https://code.google.com/archive/p/pybase/downloads

Upvotes: -1

Taku
Taku

Reputation: 33744

You can use a combination of a generator and root.after() to do your task:

from Tkinter import *

root = Tk()

root.geometry("500x500+200+200")
root.title("Epilepsy Giver")
root.resizable(width = FALSE, height = FALSE)

def get_colour():
    colours = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'violet']
    while True:
        for c in colours:
            yield c
def start():
    root.configure(background=next(colour_getter)) # set the colour to the next colour generated
    root.after(1000, start) # run this function again after 1000ms

colour_getter = get_colour()
startButton = Button(root,text="START",command=start)
startButton.pack()

root.mainloop()

Upvotes: 2

Related Questions