我有一个 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/