0

Similar to this question, I would like to save the value of a matplotlib slider when the button is clicked. Printing the value to the console is easy with print(), however I can't figure out how to save it to a variable. This is what I have tried, but it returns a value of zero before the user does anything.

def myFunction():
    fig, ax = plt.subplots()
    ax_slider = plt.axes([0.25, 0.1, 0.65, 0.03])
    lag_slider = Slider(ax=ax_slider, label='lag (s)', valmin=-15, valmax=15, valinit=0)
    def update(val):
        lag = lag_slider.val
    lag_slider.on_changed(update)
    button_ax = plt.axes([0.8, 0.025, 0.1, 0.04])
    button = Button(button_ax, 'Set Lag')

    def set_lag(val):
        lag = lag_slider.val
        print(lag) # this prints the lag value to the console, I want to return it from the function
        return lag 

    lag = button.on_clicked(set_lag)
    return lag # this executes before the button is clicked

1 Answers1

0

When you passing a function to on_clicked, the function is not executed yet, it runes whenever you click on the widget that you are using on_clicked on it.

This is the difference between calling a function, like set_lag() or just passing it, like set_lag ( Notice the parentheses ). And actually somewhere in the source codes of on_clicked function, it called the function like this:

func(event)

And in this flow, your set_lag is going to be executed.

So what happens that you can print the value, but the lag variable that you return is different? There are these reasons:

  1. You have to put your logic inside set_lag function, and do what you want to do with slider value in it.

  2. Event functions are not going to return, because the returned value is not considered anywhere. if you look at the matplotlib source code, you see that the function is just called:

for cid, func in self.observers.items():
    func(event)
  1. The value that is returned by on_click function is just an ID of the callback function you attached, to make you able to disconnect it, so it's not equal to the lag value that you are returning from your set_lag function.

So if you need it's value, you can store it into a global variable or something like that, but it doesn't help that much, becauseyou have to get noticed when the slider is clicked, by the event function you passed.

For more information, look at for "callback functions" in python ( and other languages ).

meshkati
  • 1,720
  • 2
  • 16
  • 29