Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! Check out the docs.

Print value of button

So I have a list of animals that could have future animals added on to it, so I want to iterate over the list and create a button for each animal, which I have done. However, I’m unable to get the click event to produce text of the button clicked and I’m not sure how to go about this issue. Any help would be greatly appreciated, thanks! Here is the code:

import dash
from dash.dependencies import State, Event, Input, Output
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

animals = ['Fox', 'Deer', 'Elephant', 'Cat', 'Dog']

app.layout = html.Div([
        html.Button(those, id='my-button-events-example', value=those) for those in animals

    Output('button', 'children'),
    [Input('my-button-events-example', 'value')],
    #state=[State('my-input', 'value')]
def test(value):
	return 'You pressed "{}"'.format(value)

if __name__ == '__main__':

With your code, you are producing 5 buttons with the same id=‘my-button-events-example’. Your function test() tries to listen to THE button with the given ID, but you have 5. You see the point? Which button should it listen to?

So I would give each button a unique ID, add all those IDs to the input of your call-back function and react to that (you’ll probably also have to check the n_clicks parameter of the button to check if and which button was actually clicked)


Yeah I see what you mean. Thanks for the help! Slowly but surely getting used to Dash

1 Like

As an alternative to hexor’s idea of having one callback that figures out which button was clicked, you could simply create a separate callback for each button. Here’s an example of doing that in a loop More sliders! (help with button callback example)