Starting and stopping the timer

After the timer event is bound, all you need to do is start the timer, with the method Start(milliseconds = -1, oneShot=False). The milliseconds parameter is, of course, the number of milliseconds that will elapse between the timer sending out the wx.EVT_TIMER events. Not all operating systems have system clocks with millisecond precision—if the operating system wxPython is running on does not, then the best timing available will be used. If the milliseconds parameter is -1, then the interval value when the timer was last started will be used (meaning that milliseconds actually is required the first time a wx.Timer is started). If one-Shot is True, then the timer will fire its event once and then stop itself. Otherwise, you must explicitly stop the timer with the Stop() method. The Start() method returns a Boolean value indicating success or failure in starting the timer. Starting the timer may fail under unusual circumstances on systems where timers are a limited resource. Listing 18.4 uses this mechanism to drive a digital clock, updating the display once every second.

Listing 18.4 A simple digital clock import wx import time class ClockWindow(wx.Window):

wx.Window._init_(self, parent)

self.Bind(wx.EVT_PAINT, self.OnPaint)

self.timer = wx.Timer(self) <-l Creating the timer self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) self.timer.Start(1000)

Setting time interval

Binding a timer event def Draw(self, dc): <— Drawing current time t = time.localtime(time.time()) st = time.strftime("%I:%M:%S", t) w, h = self.GetClientSize()

dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear()

dc.SetFont(wx.Font(30, wx.SWISS, wx.NORMAL, wx.NORMAL)) tw, th = dc.GetTextExtent(st) dc.DrawText(st, (w-tw)/2, (h)/2 - th/2)

def OnTimer(self, evt): <-1 Displayingthetimeeventhandler dc = wx.BufferedDC(wx.ClientDC(self)) self.Draw(dc)

def OnPaint(self, evt):

dc = wx.BufferedPaintDC(self) self.Draw(dc)

class MyFrame(wx.Frame):

wx.Frame._init_(self, None, title="wx.Timer")

ClockWindow(self)

app = wx.PySimpleApp() frm = MyFrame() frm.Show() app.MainLoop()

Was this article helpful?

0 0

Post a comment