Search code examples
pythoneventssliderwxpython

wx slider binding function returns twice


I have a slider which I want to take the position value (ie; 1, 2, 3 etc) from and use in another function. However, whenever the slider position is changed it appears to return the value of the slider twice; thus causing my other function to run twice and this slows everything down. Here is a quick example of what I mean.

import wx

class windowClass(wx.Frame):
    def __init__(self, *args, **kwargs): 
        super(windowClass, self).__init__(*args, **kwargs) 
        self.basicGUI()

    def basicGUI(self):

        panel = wx.Panel(self) 

        self.slider = wx.Slider(panel, -1, 2, 0, 4, pos=(10,25), size=(250,-1), style=wx.SL_AUTOTICKS | wx.SL_LABELS)
        sliderText = wx.StaticText(panel, -1, 'Slider', (8,8))
        self.Bind(wx.EVT_SLIDER, self.sliderUpdate)

        self.SetTitle('Sliders Window!')
        self.Show(True)

    def sliderUpdate(self, event):
        value = self.slider.GetValue()
        print value

def main():
    app = wx.App()
    windowClass(None)
    app.MainLoop()

main()

When the slider position changes I see two of the same value printed to the console as shown in the image https://i.sstatic.net/nTitP.jpg

Why is this happening?


Solution

  • If you want the slider change event to only trigger once, use these:

    self.slider.Bind(wx.EVT_COMMAND_SCROLL_THUMBTRACK, self.sliderUpdate)
    self.slider.Bind(wx.EVT_COMMAND_SCROLL_CHANGED, self.sliderUpdate)
    

    To put it simply, first one is triggered when you change the slider using your mouse, and the second one when you change the slider using keyboards. Like the other answer said, wx.EVT_SLIDER is triggered for both changing the slider and releasing your mouse.

    Take a look at this for the details about the various events associated with a slider.