2

I am creating two simple widgets with ipywidget and when displaying them, I need them to be close to each other. However the default is not showing them like this.

import ipywidgets as widgets

label = widgets.Label(value='test:')
checkbox = widgets.Checkbox(indent=False)
float_text = widgets.FloatText()

widgets_box = widgets.HBox([label, checkbox, float_text])
display(widgets_box)

Why is that? How to i put the Floattext widget just next to the checkbox?

enter image description here

GCGM
  • 901
  • 1
  • 17
  • 38

1 Answers1

0

That happens because each widget has a predefined "factory size" that is set by its internal layout property. The internal layout of a widget defines how big that component should be on the screen.

This information is used HBox and the other types of Layout Managers to figure out how much screen space each widget on the list needs. So as you can imagine, the default size of a Checkbox is quite large.

One solution to this problem is to overwrite the predefined width of large widgets when they are created by setting a custom layout with a smaller size. Here is an example:

import ipywidgets as widgets
from IPython.display import display

label = widgets.Label(value='test:', layout={'width': '30px'})
checkbox = widgets.Checkbox(indent=False, layout={'width': '20px'})
float_text = widgets.FloatText()

widgets_box = widgets.HBox([label, checkbox, float_text])
display(widgets_box)

A comparison between the original implementation and one that uses custom layouts:

enter image description here

karlphillip
  • 92,053
  • 36
  • 243
  • 426