3
votes

I am trying to create a function that will repeat a block of code three times. The code has a for loop to alter the background at 500ms intervals. I want this to be repeated three times.

for x in range(0,3):
    window.after(500, lambda: window.configure(bg = "blue"))
    window.after(1000, lambda: window.configure(bg = "green"))
    window.after(1500, lambda: window.configure(bg = "yellow"))
    window.after(2000, lambda: window.configure(bg = "purple"))
    window.after(2500, lambda: window.configure(bg = "red"))
    window.after(3000, lambda: window.configure(bg = "#a1dbcd"))
    print x

In the IDE 'x' is printed out three times but the window background only cycles once.

Can someone please help me either fix this code or find an alternate way to do it. Thanks.

2

2 Answers

0
votes

Fernando Matsumoto has answered your question, but here's a slightly more compact way to do it.

import Tkinter as tk

bgcolors = ("blue", "green", "yellow", "purple", "red", "#a1dbcd")

def cycle():
    delta = 500
    delay = delta
    for x in range(3):
        for c in bgcolors:
            window.after(delay, lambda c=c: window.configure(bg=c))
            delay += delta
        print x

window = tk.Tk()
window.pack_propagate(0)

b = tk.Button(window, text='cycle bg', command=cycle)
b.pack()

window.mainloop()
2
votes

You are calling

window.after(500, lambda: window.configure(bg = "blue"))
window.after(1000, lambda: window.configure(bg = "green"))
...

3 times. This is equivalent to writing:

window.after(500, lambda: window.configure(bg = "blue"))
window.after(500, lambda: window.configure(bg = "blue"))
window.after(500, lambda: window.configure(bg = "blue"))

After 500ms, you set the background to blue 3 times.

To do set the background in a row, add an interval every iteration. For instance, instead of

for i in range(3):
    window.after(500, lambda: window.configure(bg = "blue"))
    window.after(1000, lambda: window.configure(bg = "green"))

do

for i in range(3):
    window.after(i * 1000 + 500, lambda: window.configure(bg = "blue"))
    window.after(i * 1000 + 1000, lambda: window.configure(bg = "green"))

This code will do:

  • First iteration:

    window.after(500, lambda: window.configure(bg = "blue"))
    window.after(1000, lambda: window.configure(bg = "green"))
    
  • Second iteration:

    window.after(1500, lambda: window.configure(bg = "blue"))
    window.after(2000, lambda: window.configure(bg = "green"))
    
  • Third iteration:

    window.after(2500, lambda: window.configure(bg = "blue"))
    window.after(3000, lambda: window.configure(bg = "green"))
    

Notice how the intervals are increasing on every iteration instead of staying the same.