我正在尝试创建一个函数,该函数将重复三次代码块。该代码有一个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”被打印三次,但是窗口背景仅循环一次。
有人可以帮助我解决此代码或找到另一种方法来完成此操作。谢谢。
松本费尔南多(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()