简体   繁体   中英

Start and Stop Button on Python Tkinter window

I have created a start button as well as the stop button. After I press the start button, it runs a python program. The stop does not work until I terminate the Python code. What should I do? Here's my code:

#!/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()

These are the 2 functions I am using. I have then created a start and stop button.

The reason the stop button does not work until you close the program is because os.system blocks the calling program (it runs test.py in the foreground). Since you're calling it from a GUI that needs an active event loop, your program is hung until the test.py program completes. The solution is to use the subprocess.Popen command, which will run the test.py process in the background. The following should enable you to press the stop button after starting 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM