Search code examples
pythonpython-3.xtkinterinterrupt

Interrupting a script called within another script in tkinter


I have a program (say p1.py) which calls another python script (say p2.py) on click of a button. I would like to have a button which stops the execution of the p2.py but all the buttons freeze when it is running.

The only way to stop it is to use a keyboard interrupt in the console. I have read about the after() function but do I have to implement it in p1 or p2? Or is there any other way to do it without the after() function?

import tkinter
import os

window = tkinter.Tk()
window.title("Detecting")

def clicked():
    os.system('python extract_frames.py')

bt = tkinter.Button(window,text="Start",command=clicked)
bt.pack()

stop = tkinter.Button(window,text="Stop",command="break")     #also what command should I use for the interrupt?
stop.pack()

window.geometry('400x400')
window.mainloop()

Solution

  • You should use subprocess.Popen() instead of os.system():

    import tkinter
    import subprocess
    
    proc = None
    
    def clicked():
        global proc
        proc = subprocess.Popen(['python', 'extract_frames.py'])
    
    def kill_task():
        if proc and proc.poll() is None:
            print('killing process ...')
            proc.kill()
    
    window = tkinter.Tk()
    window.geometry('400x400')
    window.title("Detecting")
    
    bt = tkinter.Button(window, text="Start", command=clicked)
    bt.pack()
    
    stop = tkinter.Button(window, text="Stop", command=kill_task)
    stop.pack()
    
    window.mainloop()