循环后发生()函数嵌套的Python ForLoop [英] Python ForLoop with nested after() functions happening after loop

查看:367
本文介绍了循环后发生()函数嵌套的Python ForLoop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 对于范围(0,3)中的x:
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被打印出三次,但窗口背景只循环一次。

有人可以帮我解决这个问题,或者找一个替代方法来解决这个问题。
Thanks。

解决方案

Fernando Matsumoto已经回答了您的问题,但是稍微更简洁一些。 / p>

 导入Tkinter为tk 

bgcolors =(blue,green,yellow, ():
delta = 500
delay = delta
(3) ):
for bgcolors:
window.after(delay,lambda c = c:window.configure(bg = c))
delay + = delta
print x

window = tk.Tk()
window.pack_propagate(0)
$ bb = tk.Button(window,text ='cycle bg',command = cycle)
b.pack()

window.mainloop()


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.

解决方案

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

这篇关于循环后发生()函数嵌套的Python ForLoop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆