我创建了一个开始按钮以及停止按钮。按下开始按钮后,它会运行一个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()
这些是我正在使用的两个功能。然后我创建了一个开始和停止按钮。
答案 0 :(得分:2)
在关闭程序之前停止按钮不起作用的原因是因为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()