如何从子进程在 tkinter 中打印消息?

问题描述

大家!我遇到了一个问题。假设我有一个脚本,它使用 tkinter giu 的子进程模块启动,就像这样(参数包括脚本的名称):

p = Popen(['python.exe'] + params)

在执行过程中,我的脚本有一些我想在我的 gui 中打印的消息。当我使用控制台时,我只是使用这样的打印功能来完成它:

print(f'Connected to {ppm_file}')

我现在需要做的是将此消息打印在 tkinter gui 的文本小部件中。

我想这意味着使用标准输出,但我是这个概念的新手,发现它有点难以理解。

感谢您的帮助!

解决方法

在文本小部件中,您可以使用以下方法插入:

txtbox.delete('1.0',END) # to remove any preceding text(ignore if empty)
txtbox.insert(END,'Connected to {ppm_file}')  # insert the text you want
txtbox.insert(END,'\n') # additional insertion for example a newline character
,

您可以捕获外部脚本的控制台输出并将捕获的输出插入到 Text 小部件中。

下面是一个例子:

import tkinter as tk
import subprocess
import threading

root = tk.Tk()

logbox = tk.Text(root,width=80,height=20)
logbox.pack()

def capture_output():
    # "python -u" make stdout stream to be unbuffered
    p = subprocess.Popen(["python","-u","other.py"],stdout=subprocess.PIPE)
    while p.poll() is None: # process is still running
        logbox.insert("end",p.stdout.readline())
        logbox.see("end")
    logbox.insert("end","--- done ---\n")

# use thread so that it won't block the application
tk.Button(root,text="Run",command=lambda: threading.Thread(target=capture_output,daemon=True).start()).pack()

root.mainloop()