我创建了一个开始按钮和停止按钮。当我按下开始按钮后,它会运行一个Python程序。在我终止 Python 代码之前,停止不起作用。我应该怎么办?这是我的代码:
#!/usr/bin/python
import Tkinter, tkMessageBox, time
Freq = 2500
Dur = 150
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
import os
os.system("python test.py")
def stop():
print ("Stop")
top.destroy()
startButton = Tkinter.Button(top, height=2, width=20, text ="Start",
command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop",
command = stop)
startButton.pack()
stopButton.pack()
top.mainloop()
这是我正在使用的两个功能。然后我创建了一个开始和停止按钮。
停止按钮在关闭程序之前不起作用的原因是因为
os.system
阻止了调用程序(它在前台运行 test.py)。由于您是从需要活动事件循环的 GUI 调用它,因此您的程序将挂起,直到 test.py 程序完成。解决方案是使用 subprocess.Popen
命令,该命令将在后台运行 test.py 进程。以下内容应该使您能够在启动 test.py 后按停止按钮。
#!/usr/bin/python
import Tkinter, time
from subprocess import Popen
Freq = 2500
Dur = 150
top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200
def start():
import os
# os.system("python test.py")
Popen(["python", "test.py"])
def stop():
print ("Stop")
top.destroy()
startButton = Tkinter.Button(top, height=2, width=20, text ="Start",
command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop",
command = stop)
startButton.pack()
stopButton.pack()
top.mainloop()