[Tutor] How does this work?
Kent Johnson
kent37 at tds.net
Wed Feb 7 22:30:25 CET 2007
Kent Johnson wrote:
> You should be able to make the logging module work with you, it is very
> flexible. You should hook into the logging module. Write a custom
> handler that pushes log methods into your GUI. Add the handler to the
> root logger.
Here is a simple, working example of this. It creates a custom log
handler that logs to a wx.TextCtrl and sets up the logging module to log
to the custom handler and also to the console.
This is pretty much my first wx program and I whipped it together *very*
quickly (mostly copy-and-paste from the "wxPython in Action" sample
code) so no points for style, but it does work. Every time you click the
button it will generate a log event.
Kent
import logging, wx, sys
class LogToText(logging.Handler):
def __init__(self, textCtl):
logging.Handler.__init__(self)
self.textCtl = textCtl
def emit(self, record):
self.textCtl.AppendText(self.format(record))
self.textCtl.AppendText('\n')
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 250))
panel = wx.Panel(self, -1)
multiLabel = wx.StaticText(panel, -1, "Multi-line")
self.multiText = wx.TextCtrl(panel, -1,
"",
size=(200, 100), style=wx.TE_MULTILINE)
self.multiText.SetInsertionPoint(0)
self.button = wx.Button(panel, -1, "Click Me")
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([multiLabel, self.multiText, self.button])
panel.SetSizer(sizer)
def OnClick(self, event):
logging.error("Clicked")
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = TextFrame()
handler = LogToText(frame.multiText)
logger=logging.getLogger()
logger.addHandler(handler)
stdout_handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(name)s :%(asctime)s %(filename)s
%(lineno)s %(levelname)s %(message)s')
stdout_handler.setFormatter(formatter)
logger.addHandler(stdout_handler)
frame.Show()
app.MainLoop()
More information about the Tutor
mailing list