Python dash dynamic callbacks for dymanic buttons

I am new to Plotly Dash Python.I have created dynamic buttons for my application.
I want to callback those buttons and perform some operations to it.

Code:

html.Div([ 
             html.Button(name1, id='sbutton{}'.format(name1),className="sbuttons") for name1 in filelist['Key']
             ],className="sbuttonsbox"),
html.Div(id="disp_sbutton")])

It successfully creates the button as filelist['Key'] is a data frame that contains few set of values in it.

I tried to create callback but it threw following error:
code:

@app.callback(
     Output('disp_sbutton', 'children'),
     [Input("sbutton.name1",'value')]
    )
def update(input1):
return 'no data'

Error:
The element 'sbutton.name1' contains ['.'] in its ID. Periods are not allowed in IDs.

How do i created callbacks for this problem

Thanks in Advance

Welcome @rahul.k.intelli!
As the error message says, you just can’t use the . character in an ID - this is because we use periods internally to create strings id.prop in certain places. So you just need to replace the period in sbutton.name1 with another character, like _ or -, sbutton-name1 perhaps?

Hi @alexcjohnson
I am creating buttons dynamically . But i don’t know what ids it creates.
How can get it that a specific id should do a specific task…
Thanks in Advance

Ah I think I get what you’re trying to do - you basically have to do the same thing when generating the callbacks as you did generating the buttons in the first place. I’m guessing you want one big callback using all these buttons:

@app.callback(
    Output('disp_button', 'children'),
    [Input('sbutton{}'.format(name1), 'n_clicks') for name1 in filelist['Key']]
)
def update(*button_clicks):
    # here I'm assuming you just care which one was clicked most recently
    # so use dash.callback_context.triggered and ignore the n_clicks values
    return dash.callback_context.triggered[0]

This is all assuming the values in filelist['Key'] don’t have dots in them… if they do, they won’t work directly in ids, you’ll have to do something like sbutton{}.format(name1.replace('.', '-')

1 Like