如何将 tkinter 的输出打印到 GUI 而不是 CLI? [英] How do i get the output of tkinter to print into GUI instead of CLI?
问题描述
我一直在处理此代码,并将输出发送到终端.如何在 tkinter GUI 窗口中打印输出?代码如下:
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
from tkinter import *
def ping():
myinptext = entry.get()
os.system("ping "+entry.get()+" -c 2" )
myGui = Tk()
entry = StringVar()
myGui.geometry('300x300')
myGui.title("Get output inside GUI")
mylabel = Label(myGui,text="Enter target IP or host as required.").pack()
mybutton = Button(myGui,text ="Ping Test",command = ping).pack()
myEntry = Entry(myGui,textvariable=entry).pack()
myGui.mainloop()
推荐答案
使用 subprocess 而不是 os.system.有很多函数可以使用外部命令.
Use subprocess instead of os.system. There are many functions to work with external command.
我使用 subprocess.check_output()
来获取执行命令的结果.命令必须是列表 ["ping", entry.get(), "-c", "2"]
.如果使用 shell=True
,命令可以是单个字符串.
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()
顺便说一句:因为 ping
需要一些时间,所以 tkinter
将冻结这次.如果您需要非冻结版本,您将需要 subprocess
或 threading
模块中的其他功能.
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.
这篇关于如何将 tkinter 的输出打印到 GUI 而不是 CLI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!