Ckay
Ckay

Reputation: 43

Run two scripts simultaneously in tkinter

I need two scripts two run simultaneously on click of a single button. Cannot use two buttons because the gui freezes after the first button click and waits for the first program to finish. Here's the code:

import tkinter
import os
import subprocess

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

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

    # I used the subprocess approach also but it still waits for the first program to finish

    subprocess.run("python inference.py  & python extract_frames.py",shell=True)


bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

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

Upvotes: 1

Views: 1728

Answers (3)

acw1668
acw1668

Reputation: 46692

You can use two subprocess.Popen(...) to run the two scripts in separate processes:

import subprocess
import tkinter as tk

proclist = []

def clicked():
    proclist.clear()
    for script in ('inference.py', 'extract_frames.py'):
        proc = subprocess.Popen(['python', script])
        proclist.append(proc)

def kill_tasks():
    for proc in proclist:
        if proc and proc.poll() is None:
            print('Killing process with PID', proc.pid)
            proc.kill()
    proclist.clear()

root = tk.Tk()
root.geometry('400x400')
root.title('GUI')

tk.Button(root, text='Start detecting', width=20, command=clicked).pack()
tk.Button(root, text='Kill tasks', width=20, command=kill_tasks).pack()

root.mainloop()

Upvotes: 0

Andy_101
Andy_101

Reputation: 1306

Your code will look something like this.Its just a simple implementation.

from threading import Thread
import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")
def fun1():
     os.system('python inference.py')
def fun2():
     os.system('python extract_frames.py')


def clicked():
     Thread(target = fun1).start() 
     Thread(target = fun2).start()


bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

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

Upvotes: 0

Olamide226
Olamide226

Reputation: 488

Try adjusting it as thus:

import tkinter
import os
from subprocess import call
import threading

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

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

    # I used the threading approach 

    threading.Thread(target=call, args=("python inference.py" ,), ).start()
    threading.Thread(target=call, args=("python extract_frames.py" ,), ).start()



bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

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

Upvotes: 1

Related Questions