python - 如何将打印语句重定向到 Tkinter 文本小部件

标签 python tkinter

我有一个 Python 程序,它执行一组操作并在 STDOUT 上打印响应。现在我正在编写一个 GUI,它将调用已经存在的代码,我想在 GUI 而不是 STDOUT 中打印相同的内容。为此,我将使用文本小部件。我不想修改执行任务的现有代码(此代码也被其他一些程序使用)。

有人可以告诉我如何使用这个现有的任务定义并使用它的 STDOUT 结果并将其插入文本小部件吗?在主 GUI 程序中,我想调用此任务定义并将其结果打印到 STDOUT。有没有办法使用这些信息?

最佳答案

您可能可以通过将 sys.stdout 替换为您自己的写入文本小部件的类似文件的对象来解决此问题。

例如:

import Tkinter as tk
import sys

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        toolbar = tk.Frame(self)
        toolbar.pack(side="top", fill="x")
        b1 = tk.Button(self, text="print to stdout", command=self.print_stdout)
        b2 = tk.Button(self, text="print to stderr", command=self.print_stderr)
        b1.pack(in_=toolbar, side="left")
        b2.pack(in_=toolbar, side="left")
        self.text = tk.Text(self, wrap="word")
        self.text.pack(side="top", fill="both", expand=True)
        self.text.tag_configure("stderr", foreground="#b22222")

        sys.stdout = TextRedirector(self.text, "stdout")
        sys.stderr = TextRedirector(self.text, "stderr")

    def print_stdout(self):
        '''Illustrate that using 'print' writes to stdout'''
        print "this is stdout"

    def print_stderr(self):
        '''Illustrate that we can write directly to stderr'''
        sys.stderr.write("this is stderr\n")

class TextRedirector(object):
    def __init__(self, widget, tag="stdout"):
        self.widget = widget
        self.tag = tag

    def write(self, str):
        self.widget.configure(state="normal")
        self.widget.insert("end", str, (self.tag,))
        self.widget.configure(state="disabled")

app = ExampleApp()
app.mainloop()

关于python - 如何将打印语句重定向到 Tkinter 文本小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12351786/

相关文章:

Python/Tkinter - 运行具有多个参数的函数的按钮不起作用

python - 按钮上的应用程序名称

python - 从 Python 到 R 的翻译。执行时间差异很大

python - 从 numpy 数组访问 block

python - 将通用方法放入 Python 中的抽象类是一种好习惯吗?

python - 如何在后台运行无限循环并停止它?

python - 如何不断检查 JSON 文件是否在 Python 中更新?

python - 使用 python 从表存储中检索超过 1000 行

python - 从 Python 连接 Hive 远程服务器

python-3.x - 更新标签上的文本