ipywidget interactive hiding visibility

Given a widget:

import ipywidgets
button = ipywidgets.Button()

There are two direct ways to hide the the widget, with a notable difference.

Hide and unhide the widget without affecting overall page layout:

# Turn the widget "invisible" without affecting layout
button.layout.visibility = "hidden"

# Make the widget visible again, layout unaffected
button.layout.visibility = "visible"

Hide and unhide the widget and collapse the space that the widget took up:

# Hide widget and collapse empty space
button.layout.display = "none"

# Re-add the widget, adjusting page layout as necessary.
button.layout.display = "block"

When to use each one? As a rule of thumb, use layout.visibility so the page layout is not constantly jumping around as visibility is toggled. However, for very large widgets, consider using layout.display to avoid huge blank spaces.


For more general CSS information that applies here, see What is the difference between visibility:hidden and display:none?


In addition to the accepted answer, if you want to dynamically change the visibility of a control, you can declare the layout variable and reuse.

layout_hidden  = widgets.Layout(visibility = 'hidden')
layout_visible = widgets.Layout(visibility = 'visible')

Like attach to an event:

def visible_txt(b):
    text_box.layout = layout_visible

def hidden_txt(b):
    text_box.layout = layout_hidden

btn_visible.on_click(visible_txt)
btn_hidden.on_click(hidden_txt)

Had same problem so i found in

boton.layout.visibility = 'hidden'

or

check.layout.display = 'none'

they made some changes... i got if from here Cannot create a widget whose initial state is visible=False