python - 在 tkinter 小部件中显示子进程的实时输出

标签 python python-2.7 tkinter subprocess

我的问题和这个几乎一样: Widget to Display subprocess 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)

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

如何让窗口出现在子进程开始之前并实时更新其内容?

最佳答案

终于找到了解决办法。 构建窗口后,必须添加:

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()

关于python - 在 tkinter 小部件中显示子进程的实时输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15362372/

相关文章:

python-2.7 - 使用python将一系列ppm图像转换为视频

python - 播放音频文件后 pygame 没有响应

python - 如何使带有两个for循环的python代码运行得更快(有没有一种python方法可以进行Mathematica的并行化)?

excel - 如何通过使用 "win32com.client as win32"知道excel的使用行数和列数

python - 使用 Python BeautifulSoup 单击链接

python - 使用 asdf 让 tkinter 在 macos 上使用 python 3.x

python - 即使不在 tkinter 中,如何使文本选择在文本区域中可见

python - Pandas的pivot_table计算运行索引

python - 获取与numpy中的条件匹配的行的行号

python - WrapSize 和滚动条 : widgets not drawn at startup won't draw later