Search code examples
pythonslideripywidgets

Using a singular widget for multiple functions that depend on the same parameter


I want to use a single slider widget for multiple functions that depend on the parameter, how can I go about doing it. This is what I have so far, but it's quite tacky:

def Func(c):
    Code
    return x,y,z

def Func_1(d):
    Code
    return x

interact(Func, c=widgets.FloatSlider(min,max...))
interact(Func_1, d=widgets.FloatSlider(min,max...))

I don't want to do this because this creates two separate slider I have to manually adjust to the same value, it's nonoptimal.


Solution

  • You can create a function called for example onslide, which is the callback passed into interact. Then, inside that callback function, you can call the other functions that deal with the value.

    Example:

    import ipywidgets as widgets
    from ipywidgets import interact
    
    def onslide(s):
        if s < 5:
            Func(s)
        else:
            Func_1(s)
        
    interact(onslide, s=(0.0, 10.0, 0.5))
    

    Then inside Func and Func_1 you can do value-dependent things.