如何在 Python 中停止由 tkinter 触发的循环 [英] How to stop a loop triggered by tkinter in Python

查看:55
本文介绍了如何在 Python 中停止由 tkinter 触发的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to Python and even more so to tkinter, and I decided to try to create a start and stop button for an infinite loop through Tkinter. Unfortunately, once I click start, it won't allow me to click stop. The start button remains indented, and I assume this is because the function it triggered is still running. How can I make this 2nd button stop the code?

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()

推荐答案

您正在调用 while True.长话短说,Tk() 有它自己的事件循环.因此,每当您调用某个长时间运行的进程时,它都会阻止此事件循环,您将无能为力.您可能应该使用 after

You're calling while True. Long story short, Tk() has it's own event loop. So, whenever you call some long running process it blocks this event loop and you can't do anything. You should probably use after

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

I avoided using global here by just giving an attribute to 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()

这篇关于如何在 Python 中停止由 tkinter 触发的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆