python - 你如何创建一个 Tkinter GUI 停止按钮来打破无限循环?

标签 python user-interface tkinter

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

from Tkinter import *

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

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

app = Frame(root)
app.grid()

此处“开始”按钮运行无限循环扫描,“停止”按钮应在按下时中断:

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

start.grid()
stop.grid()

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

最佳答案

您不能在运行 Tkinter 事件循环的同一线程中启动 while True: 循环。这样做会阻塞 Tkinter 的循环并导致程序卡住。

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

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 module 将是有益的。这样您的扫描功能就可以在单独的线程中执行。

关于python - 你如何创建一个 Tkinter GUI 停止按钮来打破无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27050492/

相关文章:

linux - 如何使用 Pyinstaller 为 Linux 机器创建可执行文件?

python - 向 Python 生成的 PPTX 中表格的每一行添加底线

java - 无法从类方法设置标签文本

对于单个 Unicode 字符串,Python 返回长度为 2

c++ - 没有文档/ View 体系结构的 MFC

jQuery UI 对话框 - 无法看到 closeText

python - 如何让 for 循环在 python 2.7 中与 tkinter 一起工作?

python - 如何删除 for 循环中的标签

python - 使用 boto3 对 dynamoDb 进行完整扫描

python - 如何使用 python 验证 wsdl 文档?