Redirect output from Python logger to tkinter widget -
having spent time on redirecting stdout , logging output tkinter text widget, i've decided need help. code follows:
#!/usr/bin/env python tkinter import * import logging 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 not show') print 'this show' print_some_other_stuff() def print_some_other_stuff(): logger = logging.getlogger('print_some_other_stuff') logger.info('this not show') print 'this show' def main(): logger = logging.getlogger('main') root = tk() app = app(root) root.mainloop() if __name__=='__main__': main()
i know 1 can define new logging handler based on text widget can't working. function "print_stuff" wrapper around many different functions having own logger set up. need help defining new logging handler "global" can instantiated each of functions having own logger. help much appreciated.
just create sure understand correctly:
you want print logging messages both stdout , tkinter text widget logging won't print in standard console.
if indeed problem here's how it.
first let's create simple console in tkinter, text widget i'm including completeness:
class logdisplay(tk.labelframe): """a simple 'console' place @ bottom of 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)
now let's override logging handlers redirect console in parameter , still automatically print stdout:
class loggingtogui(logging.handler): """ used redirect logging output widget passed in parameters """ def __init__(self, console): logging.handler.__init__(self) self.console = console #any text widget, can utilize class above or not def emit(self, message): # overwrites default handler's emit method formattedmessage = self.format(message) #you can alter format here # disabling states no user can write in self.console.configure(state=tk.normal) self.console.insert(tk.end, formattedmessage) #inserting logger message in widget self.console.configure(state=tk.disabled) self.console.see(tk.end) print(message) #you can print stdout in overriden emit no need black magic
hope helps.
python tkinter
No comments:
Post a Comment