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

编程入门 行业动态 更新时间:2024-10-21 09:16:27
本文介绍了在 tkinter 小部件中显示子进程的实时输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的问题和这个差不多:显示子进程标准输出的小部件?但更进一步.

My question is almost the same as this one: Widget to Display subprocess stdout? but a step further.

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

I have the following code (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 窗口仅在子进程结束后出现!!

The output from the "longrunning" bash script is captured in realtime (appear in the console) but the Tkinter window appear only after the end of the subprocess !!

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

How can I have the window appearing before the subprocess start and update its content in realtime ?

推荐答案

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

Finally I found the solution. After the window construction, you must add :

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

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

And then after every line insertion in the widget, you must also force a refresh with the same method only on the widget.

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

更多推荐

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

本文发布于:2023-11-02 14:37:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部件   实时   进程   tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!