stdout to tkinter GUI

前端 未结 3 1209
甜味超标
甜味超标 2020-11-30 12:57

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

3条回答
  •  旧巷少年郎
    2020-11-30 13:21

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

提交回复
热议问题