[Python] How to make a callback function that draws a graph with a python dash button works

Discussão em 'Python' iniciado por Stack, Junho 26, 2025.

  1. Stack

    Stack Membro Participativo

    I want to draw a graph when I press the python dash button. So I created a button called btn-run and a callback function called btn_run_click. However, a new plot is not drawn when the button is pressed. The code is attached below. Is there someone who can help?

    import dash
    from dash import Dash, dcc, html, Input, Output
    import plotly.express as px
    import pandas as pd

    app = dash.Dash(__name__)

    app.layout = html.Div([
    html.Br(),
    html.Button('start', id='btn-run', n_clicks=0,
    style={'width':'150px','height':'30px'}),
    dcc.Graph(id='main-plot', figure={}),
    html.Br()
    ])

    @app.callback(
    Output('main-plot', 'children'),
    Input('btn-run','n_clicks')
    )
    def btn_run_click(btn_run):

    if btn_run == 0 : return
    df = pd.DataFrame({
    "Fruits":['Apples', 'Oranges', 'Bananas'],
    "Amount":[4,3,6]
    })

    fig = px.bar(df, x = "Fruits", y = "Amount", barmode='group')
    return dcc.Graph(figure=fig)

    if __name__ == '__main__':
    app.run_server(debug=False, port=8052)

    Continue reading...

Compartilhe esta Página