Search code examples
pythonipythonipywidgetspython-interactive

Jupyter interact ipywidgets: several widgets for one argument


Is it possible to link several widgets to one argument?
I have these three boolean widgets:

import ipywidgets as widgets
from ipywidgets import interact, fixed

w1 = widgets.Checkbox(value=False, description='Widget 1')
w2 = widgets.Checkbox(value=False, description='Widget 2')
w3 = widgets.Checkbox(value=False, description='Widget 3')

The function I'm trying to call with interact has an argument that is a list of three bools. For example:

def test(x, data):
   if all(data):
      # do something

Now I tried using interact by e.g. interact(test, x=fixed(3), data=[w1, w2, w3]); but it gives the error

'Checkbox' object is not iterable

Is there any way that I can link those three widgets to the single argument data? I have to keep this argument as a list of bools.


Solution

  • You can do something like this:

    import ipywidgets as widgets
    from ipywidgets import interact, fixed
    
    w1 = widgets.Checkbox(value=False, description='Widget 1')
    w2 = widgets.Checkbox(value=False, description='Widget 2')
    w3 = widgets.Checkbox(value=False, description='Widget 3')
    
    def test(**kwargs):
        x = kwargs.pop('val')
        if all(kwargs.values()):
            print(x)
          # do something
    
    interact(test, val = fixed(3), w1=w1, w2=w2, w3=w3);