如何将打印语句重定向到 Tkinter 文本小部件 [英] How to redirect print statements to Tkinter text widget

查看:74
本文介绍了如何将打印语句重定向到 Tkinter 文本小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Python program which performs a set of operations and prints the response on STDOUT. Now I am writing a GUI which will call that already existing code and I want to print the same contents in the GUI instead of STDOUT. I will be using the Text widget for this purpose. I do not want to modify my existing code which does the task (This code is used by some other programs as well).

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

Can someone please point me to how I can use this existing task definition and use its STDOUT result and insert it into a text widget? In the main GUI program I want to call this task definition and print its results to STDOUT. Is there a way to use this information?

推荐答案

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

You can probably solve this by replacing sys.stdout with your own file-like object that writes to the text widget.

例如:

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

这篇关于如何将打印语句重定向到 Tkinter 文本小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆