Is there any way to define absolute position of a widget in ipywidgets?

Viewed 152

I would like to define some widgets at absolute position within a layout in ipywidgets. The Box layout in ipywidgets allows me to add children but only in a sequential way. For example, I want to put button 2 at lower right corner of button 1, but the following codes only place button 2 after button 1.

import ipywidgets as widgets
box = widgets.Box(layout=widgets.Layout(width='400px', height='200px'))
button1 = widgets.Button(layout=widgets.Layout(top='30px', left='20px', width='100px', height='30px'), description="Button1")
button2 = widgets.Button(layout=widgets.Layout(top='60px', left='120px', width='100px', height='30px'), description="Button2")
box.children += (button1, button2)
box

I tried the following command but fail to make the widget use the absolute position.

button2 = widgets.Button(layout=widgets.Layout(position="absolute", top='60px', left='120px', width='100px', height='30px'), description="Button2")
button2.style.position = "absolute"

Is there any way to put widgets at absolute position?

1 Answers

You can make use of the GridBox for more complex placement:

https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Styling.html#The-Grid-layout

from ipywidgets import *
button1  = Button(description='Top left',
                 layout=Layout(width='auto', grid_area='tl'),
                 style=ButtonStyle(button_color='lightblue'))
button2  = Button(description='Bottom right',
                 layout=Layout(width='auto', grid_area='br'),
                 style=ButtonStyle(button_color='lightblue'))
GridBox(children=[button1, button2],
        layout=Layout(
            width='50%',
            grid_template_rows='auto auto',
            grid_template_columns='50% 50%',
            grid_template_areas='''
            "tl tr"
            "bl br"
            ''')
       )

enter image description here

Related