Black Lives Matter. Please consider donating to Black Girls Code today.
Learn about the upcoming Dash Enterprise 4.0 release in the August 5th webinar with Chris Parmer, the Inventor of Dash.

How to get current active Shape?

Hello,

Does someone know how to programmatically know which editable shape is currently activated ?

I would like to allow the user to delete the selected shape by clicking a button. The only way found, was by forcing the user to first move the shape (the fillcolor is changed to red using the “on_change” callback). Then, I can detect the Red shape and delete it.
My approach is not elegant and apparently, the callback “on_change” is lost after the first click on the button (probably because the way I use to delete the shape but I haven’t found any proposal in the documentation)

Any help is more than welcome !

Patrick

import plotly.graph_objects as go
from ipywidgets import Button, VBox
fig = go.FigureWidget()

# Set axes properties
fig.update_xaxes(range=[0, 7], showgrid=False)
fig.update_yaxes(range=[0, 3.5])


shp1 = go.layout.Shape(
    type="rect",
    x0=1,
    y0=1,
    x1=2,
    y1=3,
    fillcolor="Blue",
    editable=True)

shp2 = go.layout.Shape(
    type="rect",
    x0=3,
    y0=1,
    x1=6,
    y1=2,
    fillcolor="Blue",
    editable=True)

# Add shapes
fig.add_shape(shp1)
fig.add_shape(shp2)
fig.update_shapes(dict(xref='x', yref='y'))

def change_color(shp,*args,**kwargs):
    shp.update(dict(fillcolor='Red'))

def delete_shapes(*args,**kwargs):
    with output:
        try:
            list_shapes=[shp for shp in fig.layout.shapes if shp.fillcolor!='Red']
            self.fig.update_layout(shapes=list_shapes)
        except Exception as e:
            raise e
        
        
for shp in fig.layout.shapes:
    shp.on_change(change_color,'x0','y0','x1','y1')

button.on_click(delete_shapes)
VBox([button,fig])