Search code examples
pythonjupyter-notebookjupyteripywidgets

Exiting ipywidgets interact / interactive to produce a final output in jupyter notebook


I'd like to have an analogy to the %matplotlib notebook magic for matplotlib plots. It features a "power button" at the top right - and after clicking it, the UI disappears, and the output becomes a PNG of the final view.

Suppose I have a function to filter a dataframe using a value from an int slider:

from ipywidgets import interact
# df = pd.read_csv('...')

@interact(zone=(-1, 12))
def show(zone):
    if zone > 0:
        return df[df.ZoneId == zone]  # show filtered results

    if zone == 0:
        return df  # show all results

    # HERE: I want to exit the interaction, and make the int slider disappear, and the whole
    # of df to become the rendered output

I have tried creating the slider and bind it to something:

zone_slider = IntSlider(0, -1, 12)
@interact(zone=zone_slider)
def show(zone):
    # ...
    zone_slider.close()  # slider disappears, but output is still the same `interactive`.

I'd like the output to be saved with the notebook, and (after closing the notebook and opening it with a new kernel) to be displayed without the need to run any code (nor doing the interaction). Right now it only gets displayed as intearctive(children=[IntSlider(...), Output(...)], ...).

I'd like a general solution (finishing any interaction, when e.g. a Checkbox becomes True). I'm not sure if it's possible to do without resorting to lower level ipywidgets.interactive function or interact_manual, but I don't know how to use these anyway.


Solution

  • 1 - How do you programmatically remove the UI and leave only the outputs

    You can adapt this answer to hide/show the widgets. On the code_toggle function, you can add code like this:

    $('div.widget-slider').hide();
    

    You'll have to do it for each type of widget you use. Don't forget to add .show() as well.

    2 - how do you keep the interactive output on the saved notebook, instead of 'interactive(children...'.

    I found a more specific question for that, which was unanswered, and I answered it here. Basically, it is a hack to call the action from the menu item WidgetsSave Notebook Widget State.