stdout to tkinter GUI

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

How can I redirect stdout data to a tkinter Text widget?

回答1:

You need to make a file-like class whose write method writes to the Tkinter widget instead, and then do sys.stdout = . See this question.

Example (copied from the link):

class IORedirector(object):     '''A general class for redirecting I/O to this Text widget.'''     def __init__(self,text_area):         self.text_area = text_area  class StdoutRedirector(IORedirector):     '''A class for redirecting stdout to this Text widget.'''     def write(self,str):         self.text_area.write(str,False) 

and then, in your Tkinter widget:

# To start redirecting stdout: import sys sys.stdout = StdoutRedirector( self ) # (where self refers to the widget)  # To stop redirecting stdout: sys.stdout = sys.__stdout__ 


回答2:

This is an old question, but I found a solution which I would like to share with the community. My example pipes a listing of the working directory to a Tk window. I am using Python 3.6 on Windows 8. I ran the code through both Jupyter Notebook and Eclipse using Pydev.

import os from tkinter import * from subprocess import Popen, PIPE root = Tk() text = Text(root) text.pack()  def ls_proc():     return Popen(['ls'], stdout=PIPE)  with dir_proc() as p:     if p.stdout:         for line in p.stdout:             text.insert(END, line)     if p.stderr:         for line in p.stderr:             text.insert(END, line)  root.mainloop() 


文章来源: stdout to tkinter GUI
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!