Search code examples
multithreadingbuttonwhile-loopwxpython

WXPYTHON tricky


I have a textctrl box - I am reading data from it continuously every 1 second. I have a button which have to be enabled when the value drops below 50. I have a piece of code, which is making the GUI irresponsive. In the code I am presenting here, I am waiting until the value is less than 50. Then Enabling the start button

    while self.pressure_text_control.GetValue()>50:
        self.start.Disable()
        time.sleep(1)
    self.start.Enable()

This whole code is inside an another button event.

   def OnDone(self, event):
        self.WriteToControllerButton([0x04])
        self.status_text.SetLabel('PRESSURE CALIBRATION DONE \n DUMP PRESSURE')
        self.led1.SetBackgroundColour('GREY')
        self.done.Disable()
        self.add_pressure.Disable()
        while self.pressure_text_control.GetValue()>50:
            self.start.Disable()
            time.sleep(1)
        self.start.Enable()

The value in pressure_text_control is getting updated every 1 second.


Solution

  • Set up a wx.timer to do the work for you, this will free up the GUI main-loop i.e. make it responsive.
    The wx.Timer class allows you to execute code at specified intervals. https://wxpython.org/Phoenix/docs/html/wx.Timer.html

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.timer.Start(1000)
    
    def OnTimer(self, event):
        "Check the value of self.pressure_text_control here and do whatever"
    

    Don't forget to self.timer.Stop() before closing the program.