Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中停止tkinter触发的循环_Python_Tkinter - Fatal编程技术网

如何在Python中停止tkinter触发的循环

如何在Python中停止tkinter触发的循环,python,tkinter,Python,Tkinter,我不熟悉Python,对tkinter更是如此,我决定尝试为tkinter中的无限循环创建一个开始和停止按钮。不幸的是,一旦我单击“开始”,它将不允许我单击“停止”。“开始”按钮仍然缩进,我认为这是因为它触发的功能仍在运行。如何使第二个按钮停止代码 import tkinter def loop(): global stop stop = False while True: if stop == True: break

我不熟悉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()

您正在调用
,而True
。长话短说,
Tk()
有自己的事件循环。所以,无论何时调用某个长时间运行的进程,它都会阻塞此事件循环,并且您无法执行任何操作。您可能应该在

我在这里避免使用
global
,只是给
窗口提供了一个属性

e、 g-

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(等待时间,函数)?是的,时间以毫秒为单位。因此,1000=1秒。然而,这是可行的,因为循环是递归调用的,所以在Python的999最大深度达到最大值后,不会出现堆栈溢出错误吗?@ReidBarber No.Tkinter是线程化的,这只是将另一项添加到要处理的线程事件中。虽然如果您想继续单击“开始”,代码中有一个问题,但是很容易修复。