花了一些时间重定向 stdout 并将输出记录到 tkinter 文本小部件后,我决定需要一些帮助。我的代码如下:
#!/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”实际上只是许多不同函数的包装器,所有函数都设置了自己的记录器。我需要帮助定义一个新的“全局”日志记录处理程序,以便可以从每个拥有自己的记录器的函数实例化它。任何帮助深表感谢。
只是为了确保我理解正确:
您希望将日志消息打印到 STDout 和 Tkinter 文本小部件,但日志记录不会在标准控制台中打印。
如果这确实是您的问题,请按以下步骤操作。
首先让我们在 Tkinter 中创建一个非常简单的控制台,它实际上可以是任何文本小部件,但为了完整性我将其包括在内:
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:
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
希望能帮助到你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)