Search code examples
ipywidgets

ipywidgets: minimizing button width to just show icon?


I have a VBox of HBox instances, each HBox containing a Text and a Button instance:

enter image description here

Here is the code is the code I used:

        style = {'description_width': '125px', 'width': '90%'}
        for rest_id, prompt_text in fields.items():
            self.widgets[rest_id] = ipy.Text(
                    description=prompt_text,
                    disabled=False,
                    layout = ipy.Layout(width='99%'),
                    style=style)
            self.widgets[f"{rest_id}_button"] = ipy.Button(icon='cloud-upload')
            vbox_widgets.append(ipy.HBox(children=[self.widgets[rest_id], self.widgets[f"{rest_id}_button"]]))   
        self.widgets['meta_vbox'] = ipy.VBox(children=vbox_widgets)

Is there a way to fix the percentage of how much each item in an HBox gets? Or to fix an HBox element to a fixed pixel count? I want the Button instances to be just big enough to display the icon and nothing more.

thx


Solution

  • If you specify a particular width (or a dedicated Layout) for your button, then the remaining objects should adjust to fill the space, does this give what you want?:

    import ipywidgets as ipy
    fields = {'a': '1', 'b': '2'}
    widgets = {}
    vbox_widgets = []
    style = {'description_width': '125px', 'width': '90%'}
    button_layout = ipy.Layout(width='40px')
    for rest_id, prompt_text in fields.items():
        widgets[rest_id] = ipy.Text(
                description=prompt_text,
                disabled=False,
                layout = ipy.Layout(width='99%'),
                style=style)
        widgets[f"{rest_id}_button"] = ipy.Button(icon='cloud-upload', layout=button_layout)
        vbox_widgets.append(ipy.HBox(children=[widgets[rest_id], widgets[f"{rest_id}_button"]]))   
    ipy.VBox(children=vbox_widgets, layout=ipy.Layout(width='400px'))
    

    enter image description here

    For more complex layouts look at the GridBox class: https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Styling.html#The-Grid-layout

    For future questions, it's a lot easier if you include all your imports, mock out the dictionary etc. Much easier to give a response if I can just copy and paste your code and run it.