Python Tkinter 窗口上的启动和停止按钮

问题描述 投票:0回答:2

我创建了一个开始按钮和停止按钮。当我按下开始按钮后,它会运行一个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()

这是我正在使用的两个功能。然后我创建了一个开始和停止按钮。

python python-2.7 button tkinter
2个回答
3
投票

停止按钮在关闭程序之前不起作用的原因是因为

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()

0
投票

enter image description here

它不适用于 python 中的启动调试

© www.soinside.com 2019 - 2024. All rights reserved.