小编典典

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

python

我有以下代码(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)

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

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


阅读 228

收藏
2020-12-20

共1个答案

小编典典

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

frame.pack()
# force drawing of the window
win.update_idletasks()

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

# 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()
2020-12-20