基于这个答案 https://stackoverflow.com/a/5136686/7032856你可以使用下面的代码相当简单地做到这一点:
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()
鉴于该模块位于same目录。该代码将模块(最左边的条目)中的方法或函数(最右边的条目)的控制台输出作为字符串返回。然后将该字符串放入Text http://effbot.org/tkinterbook/text.htm field.
请参阅此答案返回all脚本中的方法/函数,无需显式传递方法名称 https://stackoverflow.com/a/48039105/7032856.