【问题标题】:How to stop a loop triggered by tkinter in Python如何在 Python 中停止由 tkinter 触发的循环
【发布时间】:2016-04-25 17:56:29
【问题描述】:

我是 Python 新手,对 tkinter 更是如此,因此我决定尝试为 Tkinter 的无限循环创建一个开始和停止按钮。不幸的是,一旦我点击开始,它就不允许我点击停止。开始按钮保持缩进,我认为这是因为它触发的功能仍在运行。我怎样才能让这个第二个按钮停止代码?

import tkinter

def loop():
    global stop
    stop = False
    while True:
        if stop == True:
            break
        #The repeating code
def start():
    loop()
def stop():
    global stop
    stop = True

window = tkinter.Tk()
window.title("Loop")
startButton = tkinter.Button(window, text = "Start", command = start)
stopButton = tkinter.Button(window, text = "Pause", command = stop)
startButton.pack()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    你打电话给while True。长话短说,Tk() 有自己的事件循环。所以,每当你调用某个长时间运行的进程时,它都会阻塞这个事件循环,你什么也做不了。您可能应该使用after

    我在这里避免使用global,只是给window一个属性。

    例如-

    import tkinter
    
    def stop():
    
        window.poll = False
    
    def loop():
    
        if window.poll:
            print("Polling")
            window.after(100, loop)
        else:
            print("Stopped long running process.")
    
    window = tkinter.Tk()
    window.poll = True
    window.title("Loop")
    startButton = tkinter.Button(window, text = "Start", command = loop)
    stopButton = tkinter.Button(window, text = "Pause", command = stop)
    startButton.pack()
    stopButton.pack()
    window.mainloop()
    

    【讨论】:

    • 谢谢!这在很大程度上是有道理的。我假设 after 的参数是 after(wait-time, function)?
    • 是的,时间以毫秒为单位。所以,1000 = 1 秒。
    • 这行得通,但是,由于循环被递归调用,在 Python 的 999 最大深度达到最大值后,您不会收到堆栈溢出错误吗?
    • @ReidBarber No. Tkinter 是线程化的,这只是将另一个项目添加到要处理的线程事件中。如果你想连续点击“开始”,虽然代码有问题,但是很容易解决。
    猜你喜欢
    • 2013-12-25
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2018-10-14
    • 2021-01-11
    • 1970-01-01
    相关资源
    最近更新 更多