Displaying the command line results in a Tkinter text widget
I want Python script output to Tkinter text widget instead of command line. I have this script from this StackOverflow question :
from Tkinter import * import subprocess as sub p = sub.Popen('./Scripts/Speedtest.py',stdout=sub.PIPE,stderr=sub.PIPE, shell=True) output, errors = p.communicate() root = Tk() text = Text(root) text.pack() text.insert(END, output) root.mainloop()
I added shell=true
to subprocess because I had OSError: [Errno 13] Permission denied
.
When I run the program, there will only be an empty text widget.
Edited with better solution:
Import script and call objects
from Tkinter import *
from Speedtest import ping_speed, download_speed, upload_speed
root = Tk()
text = Text(root)
text.insert(INSERT, ping_speed)
text.insert(END, download_speed)
text.pack()
mainloop()
source to share
Based on this answer , you can do it quite simply with the code below:
import subprocess # required for redirecting stdout to GUI
try:
import Tkinter as tk # required for the GUI python 2
except:
import tkinter as tk # required for the GUI python 3
def redirect(module, method):
'''Redirects stdout from the method or function in module as a string.'''
proc = subprocess.Popen(["python", "-c",
"import " + module + ";" + module + "." + method + "()"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
return out.decode('unicode_escape')
def put_in_txt():
'''Puts the redirected string in a text.'''
txt.insert('1.0', redirect(module.get(), method.get()))
if __name__ == '__main__':
root = tk.Tk()
txt = tk.Text(root)
module = tk.Entry(root)
method = tk.Entry(root)
btn = tk.Button(root, text="Redirect", command=put_in_txt)
#layout
txt.pack(fill='both', expand=True)
module.pack(fill='both', expand=True, side='left')
btn.pack(fill='both', expand=True, side='left')
method.pack(fill='both', expand=True, side='left')
root.mainloop()
given that the module is in the same directory. The code returns the console output of a method or function (rightmost entry) in a module (leftmost entry) as a string. Then it puts that line in the Text field .
See this answer for Returning all methods / functions from a script without explicitly passed method names .
source to share