[英]Python Dash - Is it possible to collapse multiple sections when pressing one button?
我有一個正在開發的儀表板應用程序。 它有 3 個按鈕,每個按鈕在單擊時折疊/展開一個部分。 我想要做的是在單擊其中一個按鈕時關閉所有其他部分。 我一直無法弄清楚如何實現這一目標。 我可以讓所有部分在按下按鈕時切換,但不能關閉。 我嘗試將 False 值傳遞給每個 output 但它總是只是切換。
如果不清楚,這里有一個例子。 如果單擊 button1,它將顯示 text1。 我想要這樣,如果我然后按下 button2,text2 將顯示,text1 將關閉。 一次只能顯示一個部分。
這是我盡可能簡單的代碼,其中每個按鈕都折疊/展開其部分。
import dash
import dash_bootstrap_components as dbc
from dash import html, Input, Output, State
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY])
server = app.server
def refresh_layout():
layout = html.Div(children=[
dbc.Row([
dbc.Col([dbc.Button(
"Button1", id="first-button", n_clicks=0, color="dark", style={"width": "100%"})]),
dbc.Col([dbc.Button(
"Button2", id="second-button", n_clicks=0, color="dark", style={"width": "100%"})]),
dbc.Col([dbc.Button(
"Button3", id="third-button", n_clicks=0, color="dark", style={"width": "100%"})]),
]),
html.Div(children=[
dbc.Collapse([
html.Div(children=[
dbc.Row([
html.H4("Text One", style={"textAlign": "center"}),
]),
]),
], id="first-collapse", is_open=False),
dbc.Collapse([
html.Div(children=[
dbc.Row([
html.H4("Text Two", style={"textAlign": "center"}),
]),
]),
], id="second-collapse", is_open=False),
dbc.Collapse([
html.Div(children=[
dbc.Row([
html.H4("Text Three", style={"textAlign": "center"}),
]),
]),
], id="third-collapse", is_open=False),
])
])
return layout
app.layout = refresh_layout
@app.callback(
Output("first-collapse", "is_open"),
Input("first-button", "n_clicks"),
State("first-collapse", "is_open"),
)
def toggle_first_collapse(num_clicks, is_open):
if num_clicks:
return not is_open
return is_open
@app.callback(
Output("second-collapse", "is_open"),
Input("second-button", "n_clicks"),
State("second-collapse", "is_open"),
)
def toggle_second_collapse(num_clicks, is_open):
if num_clicks:
return not is_open
return is_open
@app.callback(
Output("third-collapse", "is_open"),
Input("third-button", "n_clicks"),
State("third-collapse", "is_open"),
)
def toggle_third_collapse(num_clicks, is_open):
if num_clicks:
return not is_open
return is_open
if __name__ == '__main__':
app.run_server(debug=False)
謝謝你的幫助!
您可以通過單個回調來完成此操作。 我認為這應該可以解決問題。
@app.callback(
[
Output("first-collapse", "is_open"),
Output("second-collapse", "is_open"),
Output("third-collapse", "is_open"),
],
[
Input("first-button", "n_clicks"),
Input("second-button", "n_clicks"),
Input("third-button", "n_clicks"),
],
)
def toggle_collapses(button_one, button_two, button_three):
ctx = dash.callback_context
if not ctx.triggered:
raise PreventUpdate
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == 'first-button':
return True, False, False
elif button_id == 'second-button':
return False, True, False
elif button_id == 'third-button':
return False, False, True
else:
raise ValueError(f'Unexpected ID: {button_id}')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.