[英]Show command line results in Tkinter text widget
I want the output of a Python script in a Tkinter text widget instead of in the command line. 我想要在Tkinter文本小部件中而不是在命令行中输出Python脚本。 I have this script from https://stackoverflow.com/a/665598/3524043 :
我有来自https://stackoverflow.com/a/665598/3524043的脚本:
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've added shell=true
at the subprocess, cause I had a OSError: [Errno 13] Permission denied
. 我在子
OSError: [Errno 13] Permission denied
添加了shell=true
,因为我遇到了OSError: [Errno 13] Permission denied
。
When I run the program there's only an empty text widget. 当我运行程序时,只有一个空的文本小部件。
Edited with a better solution:
编辑有更好的解决方案:
Import the script and call the 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()
Based on this answer you can do it fairly simply with the below code: 根据此答案,您可以使用以下代码相当简单地完成此操作:
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 console output of a method or a function(rightmost entry) in a module(leftmost entry) as a string.
该代码以字符串形式返回模块(最左边的条目)中方法或函数(最右边的条目)的控制台输出。 It then puts that string in a Text field.
然后,将该字符串放入“ 文本”字段中。
See this answer for Returning all methods/functions from a script without explicitly passing method names . 请参阅此答案,以了解如何从脚本中返回所有方法/功能而不显式传递方法名称 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.