Python ForLoop,在循环

时间:2015-09-24 15:42:23

标签: python for-loop time tkinter

我正在尝试创建一个将重复三次代码块的函数。 代码有一个for循环,以500ms的间隔改变背景。我想要重复三次。

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

在IDE中,'x'打印出三次,但窗口背景仅循环一次。

有人可以帮我修复此代码或找到另一种方法来执行此操作。 感谢。

2 个答案:

答案 0 :(得分:2)

您正在致电

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

3次。这相当于写作:

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

500ms后,将背景设置为蓝色3次。

要连续设置背景,请在每次迭代时添加间隔。例如,而不是

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"))

此代码将执行:

  • 第一次迭代:

    window.after(500, lambda: window.configure(bg = "blue"))
    window.after(1000, lambda: window.configure(bg = "green"))
    
  • 第二次迭代:

    window.after(1500, lambda: window.configure(bg = "blue"))
    window.after(2000, lambda: window.configure(bg = "green"))
    
  • 第三次迭代:

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

注意每个迭代的间隔是如何增加的,而不是保持不变。

答案 1 :(得分:0)

Fernando Matsumoto回答了你的问题,但这是一个稍微紧凑的方法。

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()