Search code examples
pythonpython-3.xwidgetipywidgets

Python/ipywidgets functions that links multiple widgets in different functions


I am looking a for simple function that can link dynamically the 2 functions below, so that by changing the value of D or R, A will change accordingly.

from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets

dW = widgets.Dropdown(options=['2', '1'])
rW = widgets.FloatText(200)
aW = widgets.FloatText()  

@interact(D=dW, R=rW)
def print_p(D, R):
    dW = D
    rW = R 
    
@interact(A=aW)
def prin_t(A):
    aW.value = int(dW.value) * int(rW.value)

Solution

  • I think the interact is causing some confusion here, why not use a standard observe call for both dW and rW?

    import ipywidgets as widgets
    
    dW = widgets.Dropdown(options=['2', '1'])
    rW = widgets.FloatText(200)
    aW = widgets.FloatText()
    
    def change_a(_):
        aW.value = int(dW.value) * int(rW.value)
    
    dW.observe(change_a)
    rW.observe(change_a)
    
    display(widgets.VBox(children=[dW, rW, aW]))