【问题标题】:Start and Stop Button on Python Tkinter windowPython Tkinter 窗口上的开始和停止按钮
【发布时间】:2023-03-30 17:55:02
【问题描述】:

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

这是我正在使用的 2 个函数。然后我创建了一个开始和停止按钮。

【问题讨论】:

  • 你的top变量是什么?
  • Toplevel 小部件用于显示额外的应用程序窗口、对话框和其他“弹出”窗口。顶部 = Tkinter.Tk()

标签: python python-2.7 button tkinter


【解决方案1】:

在您关闭程序之前停止按钮不起作用的原因是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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2013-07-23
    • 2020-04-28
    • 2014-02-26
    • 2020-04-02
    • 2013-02-07
    • 2017-06-14
    相关资源
    最近更新 更多