Search code examples
pythonbuttonwidgetipywidgets

how to set all widgets values to default by clicking on a widget button?


Using several sliders that change some propoerties in a simulation, I'd like tu create an ipywidgets.Button that sets all sliders values to some default values, is anyone know how to do so?

from ipywidgets import FloatSlider, IntSlider, IntText, Button

A = FloatSlider(value=4, min=-10, max=20, step=0.1)
B = IntSlider(value=2, min=0, max=8, step=2)
C = IntText()

default_value_button = Button(description='click to set default values')

...

#I want this button to set specific values for A,B,C
#I need its action to be:

    A.set_state('value') = 3.7
    B.set_state('value') = 4
    C.set_state('value') = 547

...

display(A,B,C,default_value_button)

I need to set default values when I click on the button:

here's how it must look like

thank you in advance for your attention!


Solution

  • This is a simple implementation, just set a default_value attribute for the widget, and compile these widgets into a list as you create them.

    One issue with this is, if you have these widgets hooked up to an interactive function, then setting the value to default will also cause the interactive function to trigger. This might be what you want or might not be!

    from ipywidgets import *
    
    A = FloatSlider(value=4, min=-10, max=20, step=0.1)
    B = IntSlider(value=2, min=0, max=8, step=2)
    C = IntText()
    
    A.default_value = 3.7
    B.default_value = 4
    C.default_value = 547
    
    defaulting_widgets = [A,B,C]
    
    default_value_button = Button(description='click to set default values')
    
    def set_default(button):
        for widget in defaulting_widgets:
            widget.value = widget.default_value
    
    default_value_button.on_click(set_default)
    
    display(A,B,C,default_value_button)