- #!/usr/bin/env python
- #-*- coding:utf-8 -*-
- __author__ = "wangaibo168@163.com"
- import sys;
- reload(sys);
- sys.setdefaultencoding("utf-8");
- import wx;
- import random;
- import logging;
- import time;
- # 自定义日志Handler来接收日志数据
- class MyLogHandler(logging.Handler):
- def __init__(self,obj):
- logging.Handler.__init__(self);
- self.Object = obj;
- def emit(self,record):
- if record.levelno<self.level: return;
- tstr = time.strftime('%Y-%m-%d_%H:%M:%S.%U');
- self.Object.AppendText("[%s][%s] %s\\n"%(tstr,record.levelname,record.getMessage()));
- class MyFrame(wx.Frame):
- def __init__(self):
- wx.Frame.__init__(self,parent=None,title="日志窗体",pos=(100,100),size=(500,400));
- self.buildUI();
- def buildUI(self):
- self.box1 = wx.BoxSizer(wx.HORIZONTAL);
- self.text = wx.TextCtrl(parent=self,style=wx.TE_AUTO_SCROLL|wx.TE_MULTILINE);
- self.box1.Add(self.text,1,wx.ALL|wx.EXPAND,5,5);
- self.box2 = wx.BoxSizer(wx.VERTICAL);
- self.btn1 = wx.Button(parent=self,label="开始");
- self.box2.Add(self.btn1,1,wx.ALL|wx.EXPAND,5,0);
- self.btn2 = wx.Button(parent=self,label="停止");
- self.box2.Add(self.btn2,1,wx.ALL|wx.EXPAND,5,0);
- self.box1.Add(self.box2,0,wx.NORMAL,0,0);
- self.SetSizer(self.box1);
- self.text.SetEditable(False);
- self.btn1.Enable();
- self.btn2.Disable();
- self.btn1.Bind(wx.EVT_BUTTON,self.OnButton1Event);
- self.btn2.Bind(wx.EVT_BUTTON,self.OnButton2Event);
- self.timer = None;
- handler = MyLogHandler(self.text);
- logging.getLogger().addHandler(handler);
- # 通过wxpython的timer类实现测试日志数据
- def OnTimerEvent(self,event):
- # 检测日志,超过指定日志大小,就清空日志列表
- if len(self.text.GetValue())>1024:
- self.text.SetValue('');
- # 随机写入1-20个测试数据
- logging.error(''.join([random.choice(list(u"测试数据abcde12345")) for i in xrange(random.randint(1,20))]));
- def OnButton1Event(self,event):
- if self.timer:
- return;
- self.timer = wx.Timer(self);
- self.Bind(wx.EVT_TIMER,self.OnTimerEvent);
- self.timer.Start(1000);
- self.btn1.Disable();
- self.btn2.Enable();
- def OnButton2Event(self,event):
- if not self.timer:
- return;
- self.timer.Stop();
- self.timer = None;
- self.btn1.Enable();
- self.btn2.Disable();
- class MyApp(wx.App):
- def OnInit(self):
- self.win = MyFrame();
- self.win.Show(True);
- self.SetTopWindow(self.win);
- return True;
- if __name__ == "__main__":
- app = MyApp();
- app.MainLoop();
- #该片段来自于http://www.codesnippet.cn/detail/040920135593.html
来源: http://www.codesnippet.cn/detail/040920135593.html