Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatically adjust IPython widgets layout

I'm creating an interactive jupyter notebook with ipython widgets and want the user to select from a certain number of checkboxes. I'm using the code below to visualize the HBox that contains the checkboxes.

num_checks = 10

cb_cont = widgets.HBox(background_color='red',height='100px',width='100%')

checkboxes = []
for f in range(num_checks):
    checkboxes.append(\
        widgets.Checkbox(description = 'Checkbox [%d]'%(f), \
                         value=False, width=50))

cb_cont.children=[i for i in checkboxes]
display(cb_cont)

Here is a screenshot of the output from the above code:

enter image description here

As you can see, the content of the box overflows and goes beyond the width of the container.

I can change the behavior by setting the overflow_x property to be one of the following: ['visible', 'hidden', 'scroll', 'auto', 'initial', 'inherit', ''].

For instance, cb_cont.overflow_x = 'scroll' results in the following output window:

enter image description here

in which the content doesn't overflow but becomes invisible and can be scrolled.

How can I set the property of the box to visualize the content that does not fit on a newline?

Obviously I could use multiple HBox objects each one containing the maximum number of checkboxes that fit in a window size, however this is not the wanted solution for a set of reasons:

  1. Depending on the screen resolution that number could change.
  2. The number of checkboxes to pick from depends on a previous computation ans is not known it in advance.
like image 734
Matteo Avatar asked Jun 26 '26 22:06

Matteo


1 Answers

I was having the same issue with the widgets and after toying around with the various Box properties, here is what I came up with:

You need to set the following properties:

  • display: 'inline-flex'
  • flex_flow: 'row wrap'

This worked for me with any number of checkboxes (I tried up to 100). On the other hand, setting the height property was not very useful. You need the height to adapt depending on the number of checkboxes or screen resolution.

import ipywidgets as widgets
from ipywidgets import *
from IPython.display import display

num_checks = 50

cb_cont = HBox(layout=Layout(width='100%',display='inline-flex',flex_flow='row wrap'))
#cb_cont.overflow_x = 'scroll'

checkboxes = []
for f in range(num_checks):
    checkboxes.append(\
        widgets.Checkbox(description = 'Checkbox [%d]'%(f), \
                     value=False, width=50))

cb_cont.children=[i for i in checkboxes]
display(cb_cont)
like image 77
Ely Avatar answered Jun 28 '26 10:06

Ely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!