【问题标题】:Show command line results in Tkinter text widget在 Tkinter 文本小部件中显示命令行结果
【发布时间】: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


【解决方案1】:

基于this answer,您可以使用以下代码相当简单地做到这一点:

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 字段中。


查看Returning all methods/functions from a script without explicitly passing method names的这个答案。

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多