Python ForLoop with nested after() functions happening after loop

后端 未结 2 1878
伪装坚强ぢ
伪装坚强ぢ 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 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.

提交回复
热议问题