在Tkinter小部件中显示子流程的实时输出

eri*_*icc 5 python subprocess tkinter python-2.7

我的问题几乎与此相同: 显示子进程stdout的小部件? 但是更进一步。

我有以下代码(python2.7):

def btnGoClick(p1):
    params = w.line.get()
    if len(params) == 0:
        return

    # create child window
    win = tk.Toplevel()
    win.title('Bash')
    win.resizable(0, 0)
    # create a frame to be able to attach the scrollbar
    frame = ttk.Frame(win)
    # the Text widget - the size of the widget define the size of the window
    t = tk.Text(frame, width=80, bg="black", fg="green")
    t.pack(side="left", fill="both")
    s = ttk.Scrollbar(frame)
    s.pack(side="right", fill="y")
    # link the text and scrollbar widgets
    s.config(command=t.yview)
    t.config(yscrollcommand=s.set)
    frame.pack()

    process = subprocess.Popen(["<bashscript>", params], shell=False,
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    while True:
        out = process.stdout.readline()
        if out == '' and process.poll() is not None:
            break
        print out
        t.insert(tk.END, out)
Run Code Online (Sandbox Code Playgroud)

“ longrunning” bash脚本的输出是实时捕获的(显示在控制台中),但是Tkinter窗口仅在子进程结束后显示!

如何在子进程启动之前实时显示窗口并更新其内容?

eri*_*icc 4

最后我找到了解决方案。窗口构建后,您必须添加:

frame.pack()
# force drawing of the window
win.update_idletasks()
Run Code Online (Sandbox Code Playgroud)

然后,在小部件中插入每一行后,您还必须仅在小部件上使用相同的方法强制刷新。

# insert the line in the Text widget
t.insert(tk.END, out)
# force widget to display the end of the text (follow the input)
t.see(tk.END)
# force refresh of the widget to be sure that thing are displayed
t.update_idletasks()
Run Code Online (Sandbox Code Playgroud)