Search code examples
python-3.xuser-interfacewxpythonwxwidgets

Wx python update Timer interval using user input


I can't seem to find a way to update my wx timer start interval dynamically using user user input.

I am trying to create a counter program that can update the time interval for counting

enter image description here

Below is the start time definition in my Frame class

class MyFrame(wx.Frame):
    def __init__(self,parent,title):
        global interval
        super(MyFrame,self).__init__(parent,title=title,style=wx.MINIMIZE_BOX \
             | wx.SYSTEM_MENU\
             | wx.CAPTION | wx.CLOSE_BOX\
             | wx.CLIP_CHILDREN, size=(1000,1000))
        self.interval=3000
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer,self.timer)

        self.timer.Start(self.interval) 

        self.button11 = wx.Button(self, id=wx.ID_ANY, label="Cycle Time",size=(95,60))
        self.button11.Bind(wx.EVT_BUTTON, self.Cycletime)


    def Cycletime(self,e):
        global interval
        self.Pause(e)
        self.t1 = wx.TextEntryDialog(self, 'Enter Cycle time','Cycle Time',"",style=wx.OK | wx.CANCEL)
        self.t1.ShowModal()

        if self.t1.ShowModal()==wx.ID_OK:


            x_i=self.t1.GetValue()
            x_f=float(x_i)
            print(x_i)
            self.interval=x_f

The my class variable never gets updated, any suggestions?


Solution

  • You need to stop the timer and then restart it!

    import wx
    
    class MyFrame(wx.Frame):
        def __init__(self,parent,title):
            global interval
            super(MyFrame,self).__init__(parent,title=title,style=wx.MINIMIZE_BOX \
                 | wx.SYSTEM_MENU\
                 | wx.CAPTION | wx.CLOSE_BOX\
                 | wx.CLIP_CHILDREN, size=(200,200))
            self.interval=3000
            self.timer = wx.Timer(self)
            self.Bind(wx.EVT_TIMER, self.OnTimer,self.timer)
    
            self.timer.Start(self.interval)
    
            self.text = wx.StaticText(self, id=wx.ID_ANY, label="Timer",pos=(10,10))
            self.button11 = wx.Button(self, id=wx.ID_ANY, label="Cycle Time",pos=(10,60))
            self.button11.Bind(wx.EVT_BUTTON, self.Cycletime)
            self.counter = 0
            self.Show()
    
        def Cycletime(self,e):
            self.t1 = wx.TextEntryDialog(self, 'Enter Cycle time','Cycle Time',"",style=wx.OK | wx.CANCEL)
            res = self.t1.ShowModal()
            if res == wx.ID_OK:
                x_i=int(self.t1.GetValue())
                self.interval=x_i*1000
                self.timer.Stop()
                self.timer.Start(self.interval)
                print (self.interval)
            self.t1.Destroy()
    
        def OnTimer(self, evt):
            print (self.counter)
            self.counter += 1
    
    if __name__ == '__main__':
        app = wx.App()
        frame = MyFrame(None, "timer")
        app.MainLoop()