【发布时间】:2017-08-25 12:23:47
【问题描述】:
我希望在 Tkinter 文本小部件中而不是在命令行中输出 Python 脚本。我有这个来自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()
我在子进程中添加了shell=true,因为我有一个OSError: [Errno 13] Permission denied。
当我运行程序时,只有一个空的文本小部件。
用更好的解决方案编辑:
导入脚本并调用对象
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()
【问题讨论】:
-
为什么要在 Python 中将 Python 脚本作为子进程运行?
-
我认为这是正确的方法。有没有更好的方法来做到这一点?
-
你可以将
Speedtest.py作为一个模块导入你的主模块并调用你想要的对象,而不是让生活变得复杂。 -
@BillalBEGUERADJ 你是对的!感谢您的建议!
标签: python python-2.7 user-interface tkinter stdout