gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:16:11 26 4
gpt4 key购买 nike

我的问题和这个几乎一样: 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com