gpt4 book ai didi

python - Dash,如何根据点击的按钮进行回调?

转载 作者:行者123 更新时间:2023-12-03 08:43:53 24 4
gpt4 key购买 nike

我有一个动态创建一组按钮的函数:

def generate_team_button(team_shortName):
return dbc.Button(
str(team_shortName),
className="btn btn-primary",
id=str(team_shortName),
style={
"margin-right": "10px",
"margin-bottom": '10px',
},
n_clicks=0,

)

这些按钮通过循环一组项目来显示

import dash
import dash_core_components as dcc
import dash_html_components as html

import dash_bootstrap_components as dbc

from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State

import pandas as pd

data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div(
[

dbc.Row([
dbc.Col(
children=[generate_team_button(i) for i in df_teams['teams']]
),

]),

dbc.Row([
dbc.Col(
id='section',
#WANT TO UPDATE THIS SECTION BASED ON WHICH BUTTON IS BEEING CLICKED


),

]),
]
),

我想要做的是根据按下的按钮更新id=section。为此,我需要一个如下所示的 @app.callback 。但我得到的是一个元组,其中包含每个按钮被按下的次数。

@app.callback(
[
Output('league-table', 'value'),
],
[
Input(str(i), 'n_clicks') for i in df_teams['teams']
]

)

def update_league_table(*args):
print(args)
return f'{args}'

如何根据单击的按钮更新部分?

最佳答案

此信息可通过 callback_context 对象获得。这是一个小例子,

import dash
import dash_html_components as html
from dash.dependencies import Output, Input
from dash import callback_context

n_buttons = 5
# Create example app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Button {}".format(i), id=str(i)) for i in range(n_buttons)] + [html.Div(id="log")])


@app.callback(Output("log", "children"), [Input(str(i), "n_clicks") for i in range(n_buttons)])
def func(*args):
trigger = callback_context.triggered[0]
return "You clicked button {}".format(trigger["prop_id"].split(".")[0])


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

有关更多详细信息,请参阅 documentation on advanced callbacks .

关于python - Dash,如何根据点击的按钮进行回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com