簡體   English   中英

標准輸出到 tkinter GUI

[英]stdout to tkinter GUI

如何將標准輸出數據重定向到 tkinter Text 小部件?

您需要創建一個類似文件的類,其write方法改為寫入 Tkinter 小部件,然后執行sys.stdout = <your new class> 看到這個問題

示例(從鏈接復制):

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)

然后,在您的 Tkinter 小部件中:

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

# To stop redirecting stdout:
sys.stdout = sys.__stdout__

這是一個老問題,但我找到了一個解決方案,我想與社區分享。 我的示例將工作目錄列表通過管道傳輸到 Tk 窗口。 我在 Windows 8 上使用 Python 3.6。我使用 Pydev 通過 Jupyter Notebook 和 Eclipse 運行代碼。

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()
log_box_1 = tk.Text(root, borderwidth=3, relief="sunken")

with subprocess.Popen("ls -la", shell=True, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p:
            for line in p.stdout:
                log_box_1.insert(tk.END, line)

這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM