How to create a toogle button to show and clear output using ipywidgets?

Viewed 5180

I want to create a toggle button to display some output and clear it when switched in jupyter notebook using ipywidget.

I tried to do it using widgets.Output(). This however displays empty lines as I click more and more times.

Please help me out.

import ipywidgets as w
toggle = w.ToggleButton(description='click me')

out = w.Output()

def fun(obj):
    global out
    with out:
        display('asd')
    if obj['new']:  
        display(out)
    else:
        out.clear_output()
        out = w.Output()

toggle.observe(fun, 'value')
display(toggle)

1 Answers

I think the combination of global keyword with the display(out) is causing the issue here. I've simplified a little bit below:

Display the output widget in the main body of your code, and use the clear_output command (the output widget is still 'visible' but is zero height).

    import ipywidgets as w
    toggle = w.ToggleButton(description='click me')

    out = w.Output(layout=w.Layout(border = '1px solid black'))

    def fun(obj):
        with out:
            if obj['new']:  
                display('asd')
            else:
                out.clear_output()

    toggle.observe(fun, 'value')
    display(toggle)
    display(out)
Related