简体   繁体   中英

How to pass additional arguments when updating a matplotlib widget

I have multiple similar Slider s, and want to call the function update with a certain argument when a the corresponding slider is changed. Passing additional parameters should work similarly to other widgets, eg, on_clicked() of Button .

Simplified example using base code from Slider demo :

def update(val, string):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))
    print(string)
    fig.canvas.draw_idle()

freq_slider.on_changed(update("Frequency updated"))
amp_slider.on_changed(update("Amplitude updated"))

The following doesn't pass the updated val at all, and hence obviously doesn't work. According to the documentation on_changed only accepts a callable function as a parameter. Is there a way to solve this without somehow incorporating mpl_connect , eg using a lambda function?

You can use lambda to call update with additional parameters. Note that new_val is actually the current value of the slider here.

freq_slider.on_changed(lambda new_val: update(new_val, "Frequency updated"))

Below is an example using modified code from before

def update(val, string="Updated without additional string param"):
    line.set_ydata(f(t, amp_slider.val, freq_slider.val))
    print(string)
    fig.canvas.draw_idle()


freq_slider.on_changed(lambda new_val: update(new_val, "Frequency updated"))
amp_slider.on_changed(update)  # no string arg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM