How can I change the text on a button if it is clicked?

Hello there,

I’m new to Dash and I have trouble designing a button that changes its text as it is clicked. In my app I want to use a button that can be clicked to determine whether automatic updates of the dashboard are turned on or off. Therefore, I want the text on the button to say either “Start Automatic Refreshing” or “Stop Automatic Refreshing” depending on the current mode of the dashboard. I already figured out how to change the style of the button, i.e., in my case change its color from green to red but I cannot manage to change the text displayed on it. Is there a way to implement this? E.g., does the text attribute have a name that I can use to change it? I’ve tried “title” and “name” but those two do not seem to be related to the actual displayed text. Here are the relevant parts of my code:

green_button_style = {'background-color': 'green',
                      'color': 'white',
                      'height': '50px',
                      'width': '200px'}

red_button_style = {'background-color': 'red',
                    'color': 'white',
                    'height': '50px',
                    'width': '200px'}

app.layout = html.Div(children=[
    html.Button("Start Automatic Refreshing", id="refresh_button", n_clicks=0, style=green_button_style)
])

@app.callback(
    [Output('refresh_button', 'title'),
     Output('refresh_button', 'style')],
    [Input('refresh_button', 'n_clicks')])
def update_button(n_clicks):
    bool_disabled = n_clicks % 2
    if bool_disabled:
        return "Start Automatic Refreshing", green_button_style
    else:
        return "Stop Automatic Refreshing", red_button_style 

When running this code the button changes its color as it is pushed but the text does not change.

Any help is much appreciated!
Thanks in advance :slight_smile:

Hi @ttd and welcome to the Dash community :slight_smile:

The prop you are looking for is called children

So the first output under the callback decorator would be:

Output('refresh_button', 'children')

My button now behaves as I envisioned, thank you so much! :slight_smile:

1 Like