因此,我有一个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将会是有益的,这样您的scanning
函数可以在单独的线程中执行。