def __init__(self, parent, update_callback, multiprocessing=False): self.update_callback = update_callback # start tracking progress self.start_time = time.time() self.end_times = None self.current_module_name = '' self.pause_start_time = None self.previous_pauses_duration = 0.0 self.image_set_index = 0 self.num_image_sets = 1 # for multiprocessing computation self.num_jobs = 1 self.num_received = 0 self.multiprocessing = multiprocessing timer_id = wx.NewId() self.timer = wx.Timer(parent, timer_id) self.timer.Start(500) if not multiprocessing: wx.EVT_TIMER(parent, timer_id, self.update) self.update() else: wx.EVT_TIMER(parent, timer_id, self.update_multiprocessing) self.update_multiprocessing()
def __init__(self, parent, connID, name, ip, port): wx.Panel.__init__(self, parent) self.connID = connID self.name = name self.ip = ip self.port = port #t = wx.StaticText(self, -1, "This is a PageOne object %s" % ip, (20,20)) sizer = wx.BoxSizer(wx.HORIZONTAL) #left side panel_left = wx.Panel(self) sizer_left = wx.BoxSizer(wx.VERTICAL) self.text = wx.TextCtrl( panel_left, self.ID_TXT, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE ^ wx.TE_READONLY ^ wx.SUNKEN_BORDER ^ wx.TE_RICH ^ wx.HSCROLL) font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, "fixedsys", wx.FONTENCODING_SYSTEM) textattrib = wx.TextAttr(wx.BLACK, wx.NullColour, font, wx.TEXT_ALIGNMENT_DEFAULT) self.text.SetDefaultStyle(textattrib) sizer_left.Add(self.text, 1, wx.EXPAND) self.texti = wx.TextCtrl(panel_left, self.ID_TXT, "", wx.DefaultPosition, wx.DefaultSize) sizer_left.Add(self.texti, 0, wx.EXPAND) panel_left.SetSizer(sizer_left) sizer.Add(panel_left, 1, wx.EXPAND) #right side sizer_right = wx.BoxSizer(wx.VERTICAL) sizer_right.SetMinSize((150, 100)) panel_right = wx.Panel(self) box = wx.StaticBox(panel_right, -1, "Server Statistics") box_sizer = wx.StaticBoxSizer(box, wx.VERTICAL) self.servermode = wx.StaticText(panel_right, -1, "Mode: Internet") box_sizer.Add(self.servermode, 1, wx.EXPAND) self.serveruptime = wx.StaticText(panel_right, -1, "Uptime: 0") box_sizer.Add(self.serveruptime, 1, wx.EXPAND) sizer_right.Add(box_sizer, 0, wx.EXPAND) panel_right.SetSizer(sizer_right) sizer.Add(panel_right, 0, wx.EXPAND) self.SetSizer(sizer) # main timer self.timer = wx.Timer(self, ID_TIMER) self.timer.Start(500) wx.EVT_TIMER(self, ID_TIMER, self.OnTimer) # connect self.connect()
def handler_post_app_init(self): """AFTER we've started the GUI and performed all pre-imports, this method makes sure that all other dependencies are imported into the module namespace. We want these imports here, else the pre-imports can't do their thing. """ global GraphEditor, PythonShell from graph_editor import GraphEditor import module_kits from module_kits.wx_kit.python_shell import PythonShell self.start_graph_editor() # setup wx-based testing if necessary if self._devide_app.main_config.test: wx.EVT_TIMER(self, 999999, self._handler_test_all) self.timer = wx.Timer(self, 999999) self.timer.Start(150, True) if self._devide_app.main_config.load_network: # you have to keep a binding to the timer like this, or it # doesn't work at all. self.timer_ln = wx.Timer(self, -1) # now bind the timer event self.Bind(wx.EVT_TIMER, self._handler_load_network_at_startup, self.timer_ln) # then tell the timer to trigger it in 150ms self.timer_ln.Start(150, True)
def __init__(self, parent): wx.Panel.__init__(self, parent) #magic to stop the flickering def SetCompositeMode(self, on=True): exstyle = win32api.GetWindowLong(self.GetHandle(), win32con.GWL_EXSTYLE) if on: exstyle |= win32con.WS_EX_COMPOSITED else: exstyle &= ~win32con.WS_EX_COMPOSITED win32api.SetWindowLong(self.GetHandle(), win32con.GWL_EXSTYLE, exstyle) SetCompositeMode(self, True) #self.capture = cv.CaptureFromCAM(0) # turn on the webcam #img = ImagePro # Convert the raw image data to something wxpython can handle. #cv.CvtColor(img, img, cv.CV_BGR2RGB) # fix color distortions storage = cv.CreateMat(orig.width, 1, cv.CV_32FC3) self.ImagePro(capture, orig, processed, storage, grid) cv.CvtColor(orig, orig, cv.CV_BGR2RGB) self.bmp = wx.BitmapFromBuffer(640, 300, orig.tostring()) sbmp = wx.StaticBitmap(self, -1, bitmap=self.bmp) # Display the resulting image self.playTimer = wx.Timer(self, self.TIMER_PLAY_ID) wx.EVT_TIMER(self, self.TIMER_PLAY_ID, self.onNextFrame) fps = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FPS) if fps != 0: self.playTimer.Start(1000 / fps) # every X ms else: self.playTimer.Start(1000 / 15) # assuming 15 fps
def __init__(self, parent, id, attr=DefaultCalendarCellAttributes, style=wx.SIMPLE_BORDER): wx.PyWindow.__init__(self, parent, id, style=style | wx.WANTS_CHARS | wx.FULL_REPAINT_ON_RESIZE) self.attr = GetCalendarCellAttributes(attr) self.day = 33 self.year = 2033 self.month = 3 self.buffer = None self.needsupdate = True self.entries = () self._tipwindow = None wx.EVT_PAINT(self, self.OnPaint) wx.EVT_SIZE(self, self.OnSize) wx.EVT_ENTER_WINDOW(self, self.OnEnterWindow) wx.EVT_LEAVE_WINDOW(self, self.OnLeaveWindow) self._timer = wx.Timer(self) wx.EVT_TIMER(self, self._timer.GetId(), self.OnTimer) self.OnSize(None)
def __init__( self ): wx.Frame.__init__( self, None, wx.ID_ANY, "MWCam", style=wx.DEFAULT_FRAME_STYLE & ~wx.RESIZE_BORDER ) # Socket Cleint self.SocketClient = MWScore.SocketClient( SOCKET_CLIENT_HOST, SOCKET_CLIENT_PORT ) self.SocketClient.StartThread() # IP Camera #self.Camera = Trendnet( CAMERA_IP, CAMERA_USERNAME, CAMERA_PASSWORD ) self.Camera = DLink( CAMERA_IP, CAMERA_USERNAME, CAMERA_PASSWORD ) self.Camera.Connect() # Camera Panel self.CameraPanel = CameraPanel( self, self.Camera, self.SocketClient ) # Frame timer self.Timer = wx.Timer( self, self.ID_FRAME_REFRESH ) self.Timer.Start(10) wx.EVT_TIMER( self, self.ID_FRAME_REFRESH, self.Refresh ) # Frame Sizer self.Sizer = None self.Size() # Show frame self.Show( True )
def RunTest(self, event=None): self.n = 100 self.dT = 0.05 self.time = 2.0 * N.pi * N.arange(100) / 100.0 self.data1 = 1.0 * N.ones((100, 2)) self.data1[:, 0] = self.time self.data1[:, 1] = N.sin(self.time) Canvas = self.Canvas self.Canvas.ClearAll() self.DrawAxis() self.line = Canvas.AddLine(self.data1, LineColor="Red", LineStyle="Solid", LineWidth=2, InForeground=1) self.Canvas.Draw() self.timerID = wx.NewId() self.timer = wx.Timer(self, self.timerID) wx.EVT_TIMER(self, self.timerID, self.OnTimer) self.count = 0 self.timer.Start(int(self.dT * 1000))
def start(self, wx_app): import wx from wx import xrc res = xrc.XmlResource(os.path.join(os.path.dirname(__file__), 'gui.xrc')) self._frame = res.LoadFrame(None, 'EmptyFrame') # type: wx.Frame self._frame.SetDoubleBuffered(True) modules_sizer = self._frame.GetSizer() for module in self._modules: module_sizer = wx.StaticBoxSizer(wx.StaticBox(self._frame, label=module.title)) modules_sizer.Add(module_sizer, module.grid_pos, span=module.grid_span) module_panel = wx.Panel(self._frame) module_sizer.Add(module_panel) module.load(res, module_panel) module.root().Layout() modules_sizer.Fit(self._frame) self._frame.Show() self._frame.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self._frame.Icon = wx.Icon(os.path.join(os.path.dirname(__file__), 'icon.ico'), wx.BITMAP_TYPE_ICO) self._update_timer = wx.Timer(wx_app, 100) wx.EVT_TIMER(wx_app, self._update_timer.GetId(), self._on_update) self._update_timer.Start(250)
def __init__(self, parent, pv=None, deadTime=2500, min_val=None, max_val=None, increment=1.0, digits=-1, **kw): """ Most arguments are common with FloatSpin. Additional Arguments: pv = pv to set deadTime = delay (ms) between user typing a value into the field, and it being set to the PV """ floatspin.FloatSpin.__init__(self, parent, increment=increment, min_val=min_val, max_val=max_val, digits=digits, **kw) PVCtrlMixin.__init__(self, pv=pv, font="", fg=None, bg=None) floatspin.EVT_FLOATSPIN(parent, self.GetId(), self.OnSpin) self.deadTimer = wx.Timer(self) self.deadTime = deadTime wx.EVT_TIMER(self, self.deadTimer.GetId(), self.OnTimeout)
def printClicked(self, event): if not self.connected: print "Connect to Printer first!" return if self.print_loaded: print "Starting Print..." path, pFile = os.path.split(self.currentImagePath) self.start_print_index = self.GetFileIndex(self.GetFileList(path), pFile) self.printThread = threading.Thread( target=self.loadPrintThread.threadLoad, args=(path, self.GetFileList(path), self.start_print_index, self.rbPreview.GetValue(), self.rbLaser.GetValue(), self.laserPowerSpin.GetValue(), self.xScaleSpin.GetValue(), self.yScaleSpin.GetValue(), self.rbZControlOff.GetValue(), self.zTiltHeightSpin.GetValue(), self.zMotorSpeedSpin.GetValue(), self.zLayerHeightSpin.GetValue(), self.printerSerial)) self.printThread.start() TIMER_ID = 101 # pick a number self.timer = wx.Timer( self.panel, TIMER_ID) # message will be sent to the panel wx.EVT_TIMER(self.panel, TIMER_ID, self.on_print_timer) # call the on_timer function self.timer.Start(self.simulate_timer_ms) # x100 milliseconds else: print "Load a print first!"
def __init__(self, symbol): self.symbol = symbol self.base = symbol.split("_")[0].upper() self.alt = symbol.split("_")[1].upper() self.ticks = btceapi.getTradeHistory(self.symbol) self.last_tid = max([t.tid for t in self.ticks]) self.fig = plt.figure() self.axes = self.fig.add_subplot(111) self.bid_line, = self.axes.plot(*zip(*self.bid), linestyle='None', marker='o', color='red') self.ask_line, = self.axes.plot(*zip(*self.ask), linestyle='None', marker='o', color='green') self.fig.canvas.draw() self.timer_id = wx.NewId() self.actor = self.fig.canvas.manager.frame self.timer = wx.Timer(self.actor, id=self.timer_id) self.timer.Start(10000) # update every 10 seconds wx.EVT_TIMER(self.actor, self.timer_id, self.update) pylab.show()
def __init__(self, parent, timeout, *args, **kwargs): """ Describe the timeout dialog. """ logging.debug( u"Opening a new timeout dialog box with a duration of {0} secs.". format(timeout)) TIMER_ID = 100 self.timeout = timeout super(TimeoutDialog, self).__init__(parent=parent, \ title=_("The display settings have changed")) vbox = wx.BoxSizer(wx.VERTICAL) font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(int(1.2 * float(font.GetPointSize()))) font.SetWeight(wx.FONTWEIGHT_BOLD) self.title = wx.StaticText( self, label=_("Are the display settings applied correctly?")) self.title.SetFont(font) self.text = wx.StaticText(self) self.__SetLabelText() btns = self.CreateButtonSizer(wx.YES | wx.NO | wx.NO_DEFAULT) vbox.Add(self.title, proportion=1, flag=wx.LEFT | wx.RIGHT | wx.TOP, border=30) vbox.Add(self.text, proportion=1, flag=wx.LEFT | wx.RIGHT, border=30) vbox.Add(btns, proportion=1, flag=wx.ALL | wx.ALIGN_CENTER, border=15) self.SetSizerAndFit(vbox) self.Bind(wx.EVT_BUTTON, self.OnNo, id=wx.ID_NO) self.Bind(wx.EVT_BUTTON, self.OnYes, id=wx.ID_YES) """ Add a Timer """ self.tim = wx.Timer(self, TIMER_ID) self.tim.Start(1000) wx.EVT_TIMER(self, TIMER_ID, self.OnTimer)
def CreateTimer(self): # See "Making a render loop": # http://wiki.wxwidgets.org/Making_a_render_loop # Timer alternative to EVT_IDLE in MainFrame. self.timer = wx.Timer(self, self.timerID) self.timer.Start(10) # 10ms wx.EVT_TIMER(self, self.timerID, self.OnTimer)
def OnInit(self): model.Application.OnInit(self) reactor.startRunning() wx.EVT_TIMER(self, 999999, self.OnTimer) self.twistedTimer = wx.Timer(self, 999999) self.twistedTimer.Start(250, False) return True
def statusError(self, error): self.timer = wx.Timer(self, self.STATUS_TIMER_ID) # message will be sent to the panel self.timer.Start(2000) # x100 milliseconds wx.EVT_TIMER(self, self.STATUS_TIMER_ID, self.__resetStatusBar) # call the on_timer function self.statusBar.SetStatusText(error) self.statusBar.SetBackgroundColour("RED") self.statusBar.Refresh()
def __init__(self, size=wx.DisplaySize()): self.size = size self.width = width = 32.0 self.hx = hx = self.size[0] * 0.5 self.hy = hy = self.size[1] * 0.5 self.cycle = False wx.Frame.__init__(self, None, wx.ID_ANY, 'Warp', pos=(0, 0), size=self.size) # Setup screen self.Bind(wx.EVT_LEFT_DOWN, self.Quit) self.ShowFullScreen(True, style=wx.FULLSCREEN_ALL) self.Show(True) self.make_sides() self.make_clip() # Setup dubble buffer self.buffer = wx.EmptyBitmap(self.size[0], self.size[1]) self.offset = 0 self.sides = 3 self.count = 0 # Start draw timer self.timer = wx.Timer(self, 1) self.timer.Start(10) wx.EVT_TIMER(self, 1, self.run)
def create_timer(self): # See also "Making a render loop": # http://wiki.wxwidgets.org/Making_a_render_loop # Another way would be to use EVT_IDLE in MainFrame. self.timer = wx.Timer(self, self.timer_id) self.timer.Start(10) # 10ms timer wx.EVT_TIMER(self, self.timer_id, self.on_timer)
def set_timer(self): TIMER_ID = 10 # pick a number self.timer = wx.Timer(self, TIMER_ID) # message will be sent to the panel self.timer.Start(500) # x500 milliseconds wx.EVT_TIMER(self, TIMER_ID, self.on_timer) # call the on_timer function
def __init__(self, parent, id=-1, text=wx.EmptyString, #text in the ticker fgcolor = wx.BLACK, #text/foreground color bgcolor = wx.WHITE, #background color start=True, #if True, the ticker starts immediately ppf=2, #pixels per frame fps=20, #frames per second direction="rtl", #direction of ticking, rtl or ltr pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.NO_BORDER, name="Ticker" ): wx.PyControl.__init__(self, parent, id=id, pos=pos, size=size, style=style, name=name) self.timer = wx.Timer(owner=self) self._extent = (-1, -1) #cache value for the GetTextExtent call self._offset = 0 self._fps = fps #frames per second self._ppf = ppf #pixels per frame self.SetDirection(direction) self.SetText(text) self.SetInitialSize(size) self.SetForegroundColour(fgcolor) self.SetBackgroundColour(bgcolor) wx.EVT_TIMER(self, -1, self.OnTick) wx.EVT_PAINT(self, self.OnPaint) wx.EVT_ERASE_BACKGROUND(self, self.OnErase) if start: self.Start()
def __init__(self, parent, winid, value=0.0, title='', **kwds): """Layout similar to a bar, but provides a slider for user setting of the value. Fires off events when the user changes the value, see add_listener.""" self._state = "IDLE" # The state of the control for responding to mouse events self._processed = False wxBar.__init__(self, parent, winid, value=value, title=title, **kwds) self._listeners = [] self._bar_rect = None # The rectangle for the bar. Also see comments in __move_mouse self._ptr_rect = None # The rectangle where the pointer is drawn self._rbutton = None # Rectangle for right button self._lbutton = None # Rectangle for left button self._counter = None # Number of timer ticks since mouse down self._value_point = None # Last x position of the pointer's mark self._original_value_point = None # The pointer mark x position at the moment when mouse down occurred self._original_value = None # The value shown by the slider when mouse went down self._last_rect = None # The last value for the full rectangle (used in scaling) self._jump_value = None # X position of the mouse for a jump operation self._offset = None # Difference between the mouse pointer and the slider mark self._is_close = None # True when the mouse was clicked close to one of the vernier buttons wx.EVT_LEFT_DOWN(self, self.__left_down) wx.EVT_LEFT_UP(self, self.__left_up) wx.EVT_MOTION(self, self.__move_mouse) wx.EVT_RIGHT_UP(self, self.__right_up) self._timer = wx.Timer(self, 100) wx.EVT_TIMER(self, 100, self.__tick) self._i_have_mouse = False
def handle_timer_event(event_handler, callable, timer_id): """ Registers an event handler for the wx.EVT_TIMER-event. """ if IS_WXP4: event_handler.Bind(wx.EVT_TIMER, callable) else: wx.EVT_TIMER(event_handler, timer_id, callable)
def __init__(self, obj, event=None): id = wx.NewId() wx.Timer.__init__(self, obj, id) if event: self.OnTimer = event wx.EVT_TIMER(obj, id, self._OnTimer)
def start_auto_highlight(self): if self.timer: error_dialog('start_auto_highlight: timer alreay exists') else: self.timer = wx.Timer(self, -1) wx.EVT_TIMER(self, self.timer.GetId(), self.check_highlight) self.timer.Start(2000) # check every 2 seconds self.hilite_btn.Show(False)
def CreateTimer(self): # See "Making a render loop": # http://wiki.wxwidgets.org/Making_a_render_loop # Another approach is to use EVT_IDLE in MainFrame, # see which one fits you better. self.timer = wx.Timer(self, self.timerID) self.timer.Start(10) # 10ms wx.EVT_TIMER(self, self.timerID, self.OnTimer)
def __init__(self, parent, idwx=-1): wx.Panel.__init__(self, parent, idwx) self.lasttime = 1 self.lastbin = [0] self.lastbout = [0] self.speedin = [0] self.speedout = [0] unames = platform.uname() self.host0 = wx.StaticText(self, -1, 'time', (5, 250)) self.host1 = wx.StaticText(self, -1, unames[0], (5, 270)) self.host2 = wx.StaticText(self, -1, unames[1], (5, 290)) self.host3 = wx.StaticText(self, -1, unames[2], (5, 310)) wx.EVT_TIMER(self, -1, self.ontimer) self.timer = wx.Timer(self, -1) self.timer.Start(1000) txtheader = wx.StaticText(self, -1, 'Status', (0, 0)) font = wx.Font(16, wx.DEFAULT, wx.NORMAL, wx.BOLD) font1 = wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.BOLD) txtheader.SetFont(font) self.host2.SetFont(font1) self.host3.SetFont(font1) self.host1.SetFont(font1) self.host0.SetFont(font1) sizer = wx.BoxSizer(wx.VERTICAL) sizer.AddSpacer(15) sizer.Add(txtheader, 0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=15) self.tab1 = wx.ListCtrl(self, 0, style=wx.LC_REPORT, pos=(3, 3), size=(250, 200)) self.tab1.InsertColumn(0, 'Device', wx.LIST_FORMAT_CENTER, width=100) self.tab1.InsertColumn(1, 'Received MB', wx.LIST_FORMAT_CENTER, width=130) self.tab1.InsertColumn(2, 'Sent MB', wx.LIST_FORMAT_CENTER, width=130) self.tab1.InsertColumn(3, 'Download KB/s', wx.LIST_FORMAT_CENTER, width=120) self.tab1.InsertColumn(4, 'Uploaad KB/s', wx.LIST_FORMAT_CENTER, width=120) #self.tab1.SetBackgroundColour("#F2F1F0") sizer.Add(self.tab1, 0, wx.EXPAND) self.SetSizer(sizer)
def MeasureSingleSpectrum(self, event=None): """ Button <self.show_spectrum_button> was clicked """ button = self.show_spectrum_button if button.GetLabel() == button.__start_label__: self.StopAllJobs() # get spectrometer's settings spect_settings = self.SettingsNotebook.Spectrometer.GetSettings() # Initiate spectrometer if self.Spectrometer.SetSettings(spect_settings) == RETURN_FAIL: return self.wavelengths = self.Spectrometer.GetWavelengths() # Clearing the figure visvis.clf() def draw_spectrum(event): """Timer function """ spectrum = self.Spectrometer.AcquiredData() if spectrum == RETURN_FAIL: return # Display the spectrum ############### Take the log of spectrum ########## #spectrum = spectrum / float(spectrum.max()) #np.log10(spectrum, out=spectrum) ############################## ax = visvis.gca() ax.Clear() visvis.plot(self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") # Display the current temperature visvis.title("Temperature %d (C)" % self.Spectrometer.GetTemperature()) # Set up timer to draw spectrum TIMER_ID = wx.NewId() self.spectrum_timer = wx.Timer(self, TIMER_ID) self.spectrum_timer.Start(spect_settings["exposure_time"]) # Change button's label button.SetLabel(button.__stop_label__) wx.EVT_TIMER(self, TIMER_ID, draw_spectrum) elif button.GetLabel() == button.__stop_label__: # Stopping timer self.spectrum_timer.Stop() del self.spectrum_timer # Change button's label button.SetLabel(button.__start_label__) else: raise ValueError("Label is not recognized")
def AudioExtract(self, data): """ Perform Audio Extraction using as many threads as possible """ # Set the list of data files to be processed self.processFileList = data # Create a Timer to control the multi-thread audio extraction process self.processTimer = wx.Timer(self, ID_PROCESSTIMER) wx.EVT_TIMER(self, ID_PROCESSTIMER, self.OnTimer) # Run the time every half second self.processTimer.Start(500)
def __init__(self, parent, _larch, polltime=50): wx.MiniFrame.__init__(self, parent, -1, '') self.Show(False) self.polltime = polltime tid = wx.NewId() self.timer = wx.Timer(self, tid) wx.EVT_TIMER(self, tid, self.OnTimer) self.symtable = _larch.symtable self.wxping = self.symtable.get_symbol('_sys.wx.ping')
def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, 'Worms', pos = (0, 0), size = wx.DisplaySize()) self.frame = 0 self.clear_count = 0 self.reset_count = 0 # HTTP Server class HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_HEAD(request): request.send_response(200) request.send_header('Content-type', 'text/html') request.end_headers() def do_GET(request): self.do_GET(request) BaseHTTPServer.HTTPServer.__init__(self, ('', PORT), HTTPHandler) self.timeout = 0 self.on_size(None) self.Bind(wx.EVT_LEFT_DOWN, self.on_quit) self.Bind(wx.EVT_RIGHT_DOWN, self.on_reset) self.Bind(wx.EVT_SIZE, self.on_size) # Hide cursor self.SetCursor(wx.StockCursor(wx.CURSOR_BLANK)) #self.ShowFullScreen(True, style = wx.FULLSCREEN_ALL) self.SetBackgroundColour("black") #self.SetTransparent(100) self.clear() self.reset() self.Show(True) self.timer = wx.Timer(self, 1) self.timer.Start(1000 / 60.0) # 60Hz wx.EVT_TIMER(self, 1, self.run) self.reset_timer = wx.Timer(self, 2) self.reset_timer.Start(60000) wx.EVT_TIMER(self, 2, self.reset)
def __init__(self): # initialize the super class wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400)) # Matplotlib Figure self.fig = Figure((6, 4), 100) # bind the Figure to the backend specific canvas self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig) # add a subplot self.ax = self.fig.add_subplot(111) # limit the X and Y axes dimensions # we prefer 2 separate functions for clarity self.ax.set_ylim([0, 100]) self.ax.set_xlim([0, POINTS]) # but we want a "frozen" window (defined by y/xlim functions) self.ax.set_autoscale_on(False) # we do not want ticks on X axis self.ax.set_xticks([]) # we want a tick every 10 point on Y (101 is to have 100 too) self.ax.set_yticks(range(0, 101, 10)) # disable autoscale, since we don't want the Axes to adapt # draw a grid (it will be only for Y) self.ax.grid(True) # generates first "empty" plots self.user = [None] * POINTS self.nice = [None] * POINTS self.sys = [None] * POINTS self.idle = [None] * POINTS self.l_user, = self.ax.plot(range(POINTS), self.user, label='User %') self.l_nice, = self.ax.plot(range(POINTS), self.nice, label='Nice %') self.l_sys, = self.ax.plot(range(POINTS), self.sys, label='Sys %') self.l_idle, = self.ax.plot(range(POINTS), self.idle, label='Idle %') # add the legend self.ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10)) # force a draw on the canvas() # trick to show the grid and the legend self.canvas.draw() # save the clean background - everything but the line # is drawn and saved in the pixel buffer background self.bg = self.canvas.copy_from_bbox(self.ax.bbox) # take a snapshot of CPU usage, needed for the update algorithm self.before = self.prepare_cpu_usage() # bind events coming from timer with id = TIMER_ID # to the onTimer callback function wx.EVT_TIMER(self, TIMER_ID, self.onTimer)