【问题标题】:How can we stop an: "root.after(time.function)" loop?我们如何停止:“root.after(time.function)”循环?
【发布时间】:2020-06-08 15:36:19
【问题描述】:

你能帮我吗?我有以下代码:

    root = tkinter.Tk()
    root.geometry("100x200")
    root.resizable(0, 0)

    def loop():
        print("test")
        root.after(1000,loop)

    button=Button(root, text="Start Loop", command=loop).place(x=10,y=10)

    root.mainloop()

我想在某个时候停止 after 循环,手动或由另一个 def 自动调用。 我们怎样才能停止循环?

【问题讨论】:

  • 这本质上是递归,要停止递归函数,您可以添加一个指定停止条件的 base-case
  • 如果你保存了.after()的结果,你可以稍后调用.after_cancel()

标签: python-3.x loops


【解决方案1】:

感谢您的建议。

使用这种方法的接缝:

var=None   #I have given this variable an value 

def start_loop():
    global var
    print("test")
    button_start.configure(text="Stop Loop", command=stop_loop)
    var = root.after(1000,start_loop)   # now the variable has this value

def stop_loop():
    button_start.configure(text="Start Loop", command=start_loop)
    root.after_cancel(var)  # apply the command for this var which is the loop started early  

button_start=Button(root, text="Start Loop", command=start_loop)
button_start.place(x=10,y=10)

希望这是正确的方法,我找了很久!

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2020-08-05
    • 2022-01-11
    • 1970-01-01
    • 2014-05-30
    • 2010-09-26
    相关资源
    最近更新 更多