everyone! I've run into a problem. Let's say I have a script that is launched using subprocess module from tkinter giu like this (params includes the name of the script):
p = Popen(['python.exe'] + params)
During being executed, my script has some messages that I want to be printed in my gui. While I was using console, I just did it with print function like this:
print(f'Connected to {ppm_file}')
What I now need to do, is to make this message be printed in a text widget in tkinter gui.
I suppose it implys using stdout, but I'm a newbie to this concept and find it a little bit hard to understand.
Thanks for your help!
You can capture the console output of the external script and insert the captured output into a Text
widget.
Below is an example:
import tkinter as tk
import subprocess
import threading
root = tk.Tk()
logbox = tk.Text(root, width=80, height=20)
logbox.pack()
def capture_output():
# "python -u" make stdout stream to be unbuffered
p = subprocess.Popen(["python", "-u", "other.py"], stdout=subprocess.PIPE)
while p.poll() is None: # process is still running
logbox.insert("end", p.stdout.readline())
logbox.see("end")
logbox.insert("end", "--- done ---\n")
# use thread so that it won't block the application
tk.Button(root, text="Run", command=lambda: threading.Thread(target=capture_output, daemon=True).start()).pack()
root.mainloop()