Python ForLoop with nested after() functions happening after loop

后端 未结 2 1861
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 06:29

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

相关标签:
2条回答
  • 2020-12-21 06:59

    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()
    
    0 讨论(0)
  • 2020-12-21 07:05

    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.

    0 讨论(0)
提交回复
热议问题