Search code examples
pythonpython-2.7wxpython

Custom event listeners for wxpython widgets


as in the title, is it possible to add a custom event listener for wx widget and if so, how? More particularly I am trying to add one which listens to the changes of SelStart and SelEnd attributes of wx.Slider. Thanks!


Solution

  • Below is the code for custom listener for wx.slider, I am calling it inside other listener's handler.

    You can call this customize listener from the point where SelStart and SelEnd changing.

    import wx 
    import wx.lib.newevent
    DialogRespondEvent, EVT_DIALOG_RESPOND_EVENT = wx.lib.newevent.NewEvent()
    class Mywin(wx.Frame): 
        
        def __init__(self, parent, title): 
            super(Mywin, self).__init__(parent, title = title,size = (250,150))  
            self.InitUI() 
     
        def InitUI(self):    
            pnl = wx.Panel(self) 
            vbox = wx.BoxSizer(wx.VERTICAL) 
            self.Bind(EVT_DIALOG_RESPOND_EVENT, self.testing) 
            self.sld = wx.Slider(pnl, value = 10, minValue = 1, maxValue = 100,
            style = wx.SL_HORIZONTAL|wx.SL_LABELS) 
            
            vbox.Add(self.sld,1,flag = wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL |     wx.TOP, border = 20) 
            self.sld.Bind(wx.EVT_SLIDER, self.OnSliderScroll) 
            self.txt = wx.StaticText(pnl, label = 'Hello',style = wx.ALIGN_CENTER)                
            vbox.Add(self.txt,1,wx.ALIGN_CENTRE_HORIZONTAL) 
    
            pnl.SetSizer(vbox) 
            self.Centre() 
            self.Show(True)
    
        def testing(self,evt):
            print "you can do whatever you want here"
    
       def OnSliderScroll(self, e): 
           obj = e.GetEventObject() 
           val = obj.GetValue() 
           font = self.GetFont() 
           font.SetPointSize(self.sld.GetValue()) 
           self.txt.SetFont(font)
           evt = DialogRespondEvent()
           wx.PostEvent(self, evt)
    
    ex = wx.App() 
    Mywin(None,'Slider demo') 
    ex.MainLoop()