你如何创建一个 Tkinter GUI 停止按钮来打破无限循环? [英] How do you create a Tkinter GUI stop button to break an infinite loop?

查看:34
本文介绍了你如何创建一个 Tkinter GUI 停止按钮来打破无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个带有两个简单选项的 Tkinter GUI,一个开始和停止按钮.我已经定义了 GUI 布局:

So I have a Tkinter GUI with two simple options, a start and stop button. I have defined the GUI layout:

from Tkinter import *

def scanning():
    while True:
        print "hello"

root = Tk()
root.title("Title")
root.geometry("500x500")

app = Frame(root)
app.grid()

这里开始按钮运行无限循环扫描,停止按钮应该在按下时中断:

Here the Start button runs the infinite loop scanning, and the Stop button should break on press:

start = Button(app, text="Start Scan",command=scanning)
stop = Button(app, text="Stop",command="break")

start.grid()
stop.grid()

然而,当我点击开始按钮时,它总是被按下(假设是因为无限循环).但是,我无法点击停止按钮来跳出 while 循环.

However, when I hit the Start button, it is always pushed down (assuming because of the infinite loop). But, I cannot click on the Stop button to break out of the while loop.

推荐答案

您不能在运行 Tkinter 事件循环的同一线程中启动 while True: 循环.这样做会阻止 Tkinter 的循环并导致程序冻结.

You cannot start a while True: loop in the same thread that the Tkinter event loop is operating in. Doing so will block Tkinter's loop and cause the program to freeze.

对于一个简单的解决方案,您可以使用 Tk.after 每隔一秒左右在后台运行一个进程.下面是一个演示脚本:

For a simple solution, you could use Tk.after to run a process in the background every second or so. Below is a script to demonstrate:

from Tkinter import *

running = True  # Global flag

def scanning():
    if running:  # Only do this if the Stop button has not been clicked
        print "hello"

    # After 1 second, call scanning again (create a recursive loop)
    root.after(1000, scanning)

def start():
    """Enable scanning by setting the global flag to True."""
    global running
    running = True

def stop():
    """Stop scanning by setting the global flag to False."""
    global running
    running = False

root = Tk()
root.title("Title")
root.geometry("500x500")

app = Frame(root)
app.grid()

start = Button(app, text="Start Scan", command=start)
stop = Button(app, text="Stop", command=stop)

start.grid()
stop.grid()

root.after(1000, scanning)  # After 1 second, call scanning
root.mainloop()

当然,您可能希望将此代码重构为一个类,并让 running 成为它的一个属性.此外,如果您的程序变得复杂,那么查看 Python 的 threading 模块会很有帮助 以便您的 scanning 功能可以在单独的线程中执行.

Of course, you may want to refactor this code into a class and have running be an attribute of it. Also, if your program becomes anything complex, it would be beneficial to look into Python's threading module so that your scanning function can be executed in a separate thread.

这篇关于你如何创建一个 Tkinter GUI 停止按钮来打破无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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