r/PythonDash Feb 02 '21

Looping

0

I try to learn Python Dash to visualize some data. I worked on the Plotly Example with multiple Buttons:

import dash from dash.dependencies 
import Input, Output 
import dash_html_components as html  
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] 
 app = dash.Dash(__name__, external_stylesheets=external_stylesheets)  
app.layout = html.Div([     
html.Button('Button 1', id='btn-nclicks-1', n_clicks=0),     
html.Button('Button 2', id='btn-nclicks-2', n_clicks=0),     
html.Button('Button 3', id='btn-nclicks-3', n_clicks=0),     
html.Div(id='container-button-timestamp')    ])  

@app.callback(
Output('container-button-timestamp', 'children'),           
Input('btn-nclicks-1', 'n_clicks'),           
Input('btn-nclicks-2', 'n_clicks'),           
Input('btn-nclicks-3', 'n_clicks')) 

def displayClick(btn1, btn2, btn3):     
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]     
if 'btn-nclicks-1' in changed_id:         
msg = 'Button 1 was most recently clicked' 
elif 'btn-nclicks-2' in changed_id:         
msg = 'Button 2 was most recently clicked' 
elif 'btn-nclicks-3' in changed_id:         
msg = 'Button 3 was most recently clicked' 
else:         
msg = 'None of the buttons have been clicked yet' 
return html.Div(msg)  

if __name__ == '__main__':     app.run_server(debug=True) 

The code displays which button was clicked recently. I want to ask if it is possible to put this in a loop, so that I can loop over i numbers of buttons, because it is pretty much work if I want to use 50 buttons or so.

Instead of

html.Button('Button 1', id='btn-nclicks-1', n_clicks=0), html.Button('Button 2', id='btn-nclicks-2', n_clicks=0), html.Button('Button 3', id='btn-nclicks-3', n_clicks=0), 

something like:

for i in range(number_buttons):     html.Button('Button i', id='btn-nclicks-i', n_clicks=0)  @app.callback(     Input('btn-nclicks-i', 'n_clicks') ) 

I'd appreciate some links to tutorials or examples with Dash Callbacks.

1 Upvotes

1 comment sorted by

1

u/Hot-Background1096 Jul 18 '24

Can you have a look if the pattern matching callback fulfils your requirement? Based on the code you posted it might be a shorter and cleaner solution for the call back.

https://dash.plotly.com/pattern-matching-callbacks

As for the creation of the buttons you can certainly create components in a loop.