'How can I pass arguments to my python script in Tkinter
I want to create button to run my python script for users. Script takes few arguments from user. How can I pass these arguments to the script?
import os
from tkinter import *
window=Tk()
window.title("Configure clients")
window.geometry('550x200')
def run():
os.system('python create_client.py')
btn = Button(window, text="Click Me", bg="black", fg="white",command=run)
btn.grid(column=0, row=0)
window.mainloop()```
Solution 1:[1]
Instead of os.system, you should use subprocess.Popen.
Because os.system waits for the command to complete, it will make your launcher GUI unresponsive.
When you use subprocess.Popen it will start a new process, but it will not wait for it to end.
The first argument to the Popen constructor should be a sequence of arguments, like:
args = ["python", "create_client.py", "arg1", "arg2"]
You could get the arguments from Entry widgets.
I would propose to call Popen as follows:
import subprocess as sp
p = sp.Popen(
["python", "create_client.py", "arg1", "arg2"],
stdout=sp.PIPE, stderr=sp.PIPE, text=True
)
Save the Popen instance in a list, because you might want to do things with it later.
For example, you might want to check the eventual return value of the process. If the process exits with an error, you might want to show the standard output and/or standard error to the user.
That is also the reason for supplying sp.PIPE to stdout and stderr; it saves the output of the program.
Read the subprocess documentation. It contains much more information then can be given in an answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
