How Do I Get The Output Of Tkinter To Print Into GUI Instead Of CLI?
I have been working on with this code and I get my output to the terminal. How do i get the output to print in the tkinter GUI window insted? Here's the code: import sys import os
Solution 1:
Use subprocess instead of os.system. There are many functions to work with external command.
I use subprocess.check_output()
to get result of executed command. Command has to be as list ["ping", entry.get(), "-c", "2"]
. Command can be single string if you use shell=True
.
import tkinter as tk
import subprocess
def ping():
cmd = ["ping", entry.get(), "-c", "2"]
output = subprocess.check_output(cmd)
#output = subprocess.check_output("ping {} -c 2".format(entry.get()), shell=True)
print('>', output)
# put result in label
result['text'] = output.decode('utf-8')
my_gui = tk.Tk()
entry = tk.StringVar()
my_gui.geometry('300x300')
my_gui.title("Get output inside GUI")
tk.Label(my_gui, text="Enter target IP or host as required.").pack()
tk.Entry(my_gui, textvariable=entry).pack()
tk.Button(my_gui,text="Ping Test", command=ping).pack()
# label for ping result
result = tk.Label(my_gui)
result.pack()
my_gui.mainloop()
BTW: because ping
takes some time so tkinter
will freeze for this time. If you need non-freezing version you will need other functions in subprocess
or threading
module.
Post a Comment for "How Do I Get The Output Of Tkinter To Print Into GUI Instead Of CLI?"