将 Python 记录器的输出重定向到 tkinter 小部件 [英] Redirect output from Python logger to tkinter widget

查看:100
本文介绍了将 Python 记录器的输出重定向到 tkinter 小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将标准输出重定向和将输出记录到 tkinter 文本小部件上花了一些时间后,我决定需要一些帮助.我的代码如下:

Having spent some time on redirecting stdout and logging output to a tkinter text widget, I've decided I need some help. My code is as follows:

#!/usr/bin/env python
from Tkinter import *
import logging
from threading import Thread

class IODirector(object):
    def __init__(self,text_area):
        self.text_area = text_area

class StdoutDirector(IODirector):
    def write(self,str):
        self.text_area.insert(END,str)
    def flush(self):
        pass

class App(Frame):

    def __init__(self, master):
        self.master = master
        Frame.__init__(self,master,relief=SUNKEN,bd=2)
        self.start()

    def start(self):
        self.master.title("Test")
        self.submit = Button(self.master, text='Run', command=self.do_run, fg="red")
        self.submit.grid(row=1, column=2)
        self.text_area = Text(self.master,height=2.5,width=30,bg='light cyan')
        self.text_area.grid(row=1,column=1)

    def do_run(self):
        t = Thread(target=print_stuff)
        sys.stdout = StdoutDirector(self.text_area)
        t.start()

def print_stuff():
    logger = logging.getLogger('print_stuff')
    logger.info('This will not show')
    print 'This will show'
    print_some_other_stuff()

def print_some_other_stuff():
    logger = logging.getLogger('print_some_other_stuff')
    logger.info('This will also not show')
    print 'This will also show'

def main():    
    logger = logging.getLogger('main')
    root = Tk()
    app = App(root)
    root.mainloop() 

if __name__=='__main__':
    main()

我知道可以基于文本小部件定义新的日志处理程序,但我无法让它工作.函数print_stuff"实际上只是许多不同函数的包装器,所有函数都设置了自己的记录器.我需要帮助定义一个新的全局"日志处理程序,以便可以从每个具有自己的记录器的函数中实例化它.非常感谢任何帮助.

I know that one can define a new logging handler based on a text widget but I can't get it working. The function "print_stuff" is really just a wrapper around many different functions all having their own logger set up. I need help with defining a new logging handler that is "global" so that it can be instantiated from each of the functions having their own logger. Any help is much appreciated.

推荐答案

只是为了确保我理解正确:

Just to make sure I understand correctly:

您想将日志消息打印到 STDout 和 Tkinter 文本小部件,但日志不会在标准控制台中打印.

You want to print the logging messages both to your STDout and Tkinter text widget but the logging won't print in the standard console.

如果这确实是您的问题,这里是如何做的.

If it is indeed your problem here's how to do it.

首先让我们在 Tkinter 中创建一个非常简单的控制台,它实际上可以是任何文本小部件,但为了完整起见,我将其包括在内:

First let's make a very simple console in Tkinter, it could be any text widget really but I'm including it for completeness:

class LogDisplay(tk.LabelFrame):
"""A simple 'console' to place at the bottom of a Tkinter window """
    def __init__(self, root, **options):
        tk.LabelFrame.__init__(self, root, **options);

        "Console Text space"
        self.console = tk.Text(self, height=10)
        self.console.pack(fill=tk.BOTH)

现在让我们重写日志处理程序以重定向到参数中的控制台并仍然自动打印到 STDout:

Now let's override the logging Handlers to redirect to a console in parameter and still automatically print to STDout:

class LoggingToGUI(logging.Handler):
""" Used to redirect logging output to the widget passed in parameters """
    def __init__(self, console):
        logging.Handler.__init__(self)

        self.console = console #Any text widget, you can use the class above or not

    def emit(self, message): # Overwrites the default handler's emit method
        formattedMessage = self.format(message)  #You can change the format here

        # Disabling states so no user can write in it
        self.console.configure(state=tk.NORMAL)
        self.console.insert(tk.END, formattedMessage) #Inserting the logger message in the widget
        self.console.configure(state=tk.DISABLED)
        self.console.see(tk.END)
        print(message) #You can just print to STDout in your overriden emit no need for black magic

希望有帮助.

这篇关于将 Python 记录器的输出重定向到 tkinter 小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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