如何制作一个使用 python 破折号按钮绘制图形的回调函数

问题描述 投票:0回答:1

我想在按下 python 破折号按钮时绘制图形。 所以我创建了一个名为 btn-run 的按钮和一个名为 btn_run_click 的回调函数。 但是,按下按钮时不会绘制新图。代码附在下面。 有人可以帮忙吗?

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)
python html web
1个回答
0
投票

我对你的代码做了一些小改动

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(
    # change output to main-plot.figure
    Output('main-plot', 'figure'),
    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+btn_run, 6] 
    })

    fig = px.bar(df, x="Fruits", y="Amount", barmode='group')
    # just return the figure
    return fig


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

© www.soinside.com 2019 - 2024. All rights reserved.