Search code examples
pythonwxpythonwxwidgets

wxPython update StaticText every x seconds/minutes using timer


I'm trying to update some static text using a timer and the output of a function.

The code is here: code.

I know very little about wxPython, it's one of the many things that I just don't get and this is maddening, if I print the output of apper to console it works perfectly, all I want to do is have what prints out to the console applied to the text.

What am I doing wrong?


Solution

  • Timers can be a pain to use, an easier way is to use the functions wx.CallAfter and/or wx.CallLater - also these functions are thread-safe and can be used to invoke functions on the GUI thread from other worker threads. Here is a sample...

    import random
    import wx
    
    class Frame(wx.Frame):
        def __init__(self):
            super(Frame, self).__init__(None)
            self.SetTitle('Title')
            panel = wx.Panel(self)
            style = wx.ALIGN_CENTRE | wx.ST_NO_AUTORESIZE
            self.text = wx.StaticText(panel, style=style)
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.AddStretchSpacer(1)
            sizer.Add(self.text, 0, wx.EXPAND)
            sizer.AddStretchSpacer(1)
            panel.SetSizer(sizer)
            self.on_timer()
        def on_timer(self):
            self.text.SetLabel(str(random.randint(0, 100)))
            wx.CallLater(1000, self.on_timer)
    
    if __name__ == '__main__':
        app = wx.App()
        frame = Frame()
        frame.Show()
        app.MainLoop()