Search code examples
ipywidgets

How to control the width of buttons of ipywidgets.ToggleButtons


A basic togglebutton looks like

widgets.ToggleButtons(
    options=['Slow', 'Regular', 'Fast'],
    description='Speed:',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltips=['Description of slow', 'Description of regular', 'Description of fast'],
#     icons=['check'] * 3
)

Code comes from https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html#ToggleButtons

But that produces rather large buttons for small text.

enter image description here

I have been playing with different options for layout, but that only affects the container of the buttons.


Solution

  • As the documentation says

    While the layout attribute only exposes layout-related CSS properties for the top-level DOM element of widgets, the style attribute is used to expose non-layout related styling attributes of widgets.

    However, the properties of the style attribute are specific to each widget type.

    The solution lies in style={"button_width": "50px"}

    Example

    widgets.ToggleButtons(
        options=['A','B', 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCC'],
        disabled=False,
        button_style='info', # 'success', 'info', 'warning', 'danger' or ''
        layout=widgets.Layout(width='auto'),
        style={"button_width": "auto"},
        #     icons=['check'] * 3
    )
    
    widgets.ToggleButtons(
        options=['A','B', 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCC'],
        disabled=False,
        button_style='warning', # 'success', 'info', 'warning', 'danger' or ''
        layout=widgets.Layout(width='auto'),
        style={"button_width": "50px"},
        #     icons=['check'] * 3
    )
    

    enter image description here