Search code examples
pythonjupyter-notebookipythonipywidgets

Update displayed value everytime ipywidgets are updated


In my notebook i have 7 FloatSlider widgets. I want to have the product of these 7 widgets displayed at all times in a way that, as the user moves the sliders, the value displayed is updated. Currently i am trying to display the product of the SliderWidgets in a Widgets.Text (n), but i am not sure if it is the best solution.

 import ipywidgets as widgets

caption = widgets.Label(value='Play around with the variables to see how N changes!')   

r = widgets.FloatSlider(value=1,
                         min=1.0,
                         max=3.0,
                         step=0.1,
                         description="R*")

fp = widgets.FloatSlider(value=1,
                         min=0.35,
                         max=1.0,
                         step=0.05,
                         description="fp")

ne = widgets.FloatSlider(value=1
                         min=0.2,
                         max=3.0,
                         step=0.1,
                         description="ne")

fl = widgets.FloatSlider(value=1,
                         min=1.0,
                         max=1.3,
                         step=0.05,
                         description="fl")

fi = widgets.FloatSlider(value=1,
                         min=0.5,
                         max=1.5,
                         step=0.05,
                         description="fi")

fc = widgets.FloatSlider(value=0.20,
                         min=0.10,
                         max=0.30,
                         step=0.05,
                         description="fi",)

l = widgets.FloatSlider(value=60000000.0,
                         min=5000000.0,
                         max=1000000000.0,
                         step=5000000,
                         description="fi")


n = widgets.Text(
    value= str(int(r.value * fp.value * ne.value * fl.value * fi.value * fc.value * l.value)) + " civilizations" ,
    description='Estimated N:',
    disabled=True)

left_box = VBox([r, fp, ne,fl])
right_box = VBox([ fi,fc,l,n])
HBox([left_box, right_box])

This code that i used displays the widgets, but does not update the widget n automatically. What is the best way for me to do it, that does not involve printing a new value everytime?


Solution

  • You can use an observe and a callback function on value change for each slider

    def on_value_change(change):
        n.value = str(int(r.value * fp.value * ne.value * fl.value * fi.value * fc.value * l.value)) + " civilizations" 
    
    r.observe(on_value_change)
    fp.observe(on_value_change)
    # ...