Search code examples
pythonjupyter-labipywidgets

JupyterLab ipywidget close one widget and display another on button click


I'm new to Jupyterlab and ipywidget (and might be missing some fundamentals).
This seems to be simple, but I searched everywhere and could not find a way to do this.
I just need to close widget A and display widget B on button click event (of widget A).
This is what I have tried/need in simple terms.

import ipywidgets
from IPython.display import display

buttonA_widget = ipywidgets.Button(description='Button A')
buttonB_widget = ipywidgets.Button(description='Button B')

display(buttonA_widget)

def switchMode(x):
    buttonA_widget.close()
    display(buttonB_widget)

buttonA_widget.on_click(switchMode)


When I tried above, buttonA get disappear, but second display call does not get executed
and I don't get any error messages (trying this on Jetson Nano).
Thanks in advance...


Solution

  • You can wrap the button in an Output widget and clear it when required:

    import ipywidgets
    from IPython.display import display
    
    buttonA_widget = ipywidgets.Button(description='Button A')
    buttonB_widget = ipywidgets.Button(description='Button B')
    
    out = ipywidgets.Output()
    
    with out:
        display(buttonA_widget)
    
    
    def switchMode(x):
        out.clear_output()
        with out:
            display(buttonB_widget)
    
    
    buttonA_widget.on_click(switchMode)
    out