我写了一个显示问题的最小应用程序。我第一次点击两个按钮中的一个然后一切顺利。但是,当我单击位于导航栏上的主页图片以使用按钮恢复页面时,会出现下一个错误“在 Dash 回调的
Input
中使用了一个不存在的对象。该对象的 ID 是 `button-1 “
import dash
from dash.dependencies import Input, Output
from dash import callback_context, html
import dash_boosted_components as dbc
from dash.exceptions import PreventUpdate
app = dash.Dash(
external_stylesheets=[
dbc.themes.BOOTSTRAP,
dbc.icons.BOOTSTRAP,
],
)
def load_buttons():
return dbc.Container(
[
dbc.Row(
[
dbc.Col(dbc.Button("Button 1", id="button-1"), width="auto"),
dbc.Col(dbc.Button("Button 2", id="button-2"), width="auto"),
], justify="center"
)
]
)
app.layout = html.Div(
[
dbc.Navbar(
dbc.NavItem(dbc.NavLink(className="bi bi-house-door-fill", id="nav-home")),
),
dbc.Row(
dbc.CardBody(load_buttons(), id="app-container"),
justify="center"
),
]
)
@app.callback(
Output("app-container", "children"),
Input("nav-home", "n_clicks"),
Input("button-1", "n_clicks"),
Input("button-2", "n_clicks")
)
def display_pages(nh, b1, b2):
ctx = callback_context
if None is not ctx.triggered:
tid = ctx.triggered[0]['prop_id'].split('.')[0]
print(tid)
if "button-1" == tid and b1:
return html.Div("Button 1")
elif "button-2" == tid and b2:
return html.Div("Button 2")
elif "nav-home" == tid and nh:
return load_buttons()
else:
raise PreventUpdate`
else:
raise PreventUpdate
if __name__ == "__main__":
app.run_server(debug=True, host="0.0.0.0", port=8082)
您对三个不同的输入使用相同的回调,当您替换“app-container”div 的内容时,id 为“button-1”和“button-2”的按钮不再存在。
尝试将按钮和导航栏链接的回调分开。
编辑:V3
import dash
from dash.dependencies import Input, Output
from dash import html
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
app = dash.Dash(
external_stylesheets=[
dbc.themes.BOOTSTRAP,
dbc.icons.BOOTSTRAP,
],
)
def load_buttons():
return dbc.Container(
[
dbc.Row(
[
dbc.Col(dbc.Button("Button 1", id="button-1"), width="auto"),
dbc.Col(dbc.Button("Button 2", id="button-2"), width="auto"),
], justify="center"
)
]
)
app.layout = html.Div(
[
dbc.Navbar(
dbc.NavItem(dbc.NavLink(className="bi bi-house-door-fill", id="nav-home")),
),
dbc.Row(
[
dbc.CardBody(load_buttons(), id="button-container"),
dbc.CardBody(id="app-container", style={"display": "none"}),
],
justify="center",
),
]
)
@app.callback(
[Output("button-container", "style"), Output("app-container", "children"), Output("app-container", "style")],
Input("nav-home", "n_clicks"),
Input("button-1", "n_clicks"),
Input("button-2", "n_clicks"),
)
def display_pages(nh, b1, b2):
ctx = dash.callback_context
if not ctx.triggered:
raise PreventUpdate
tid = ctx.triggered[0]["prop_id"].split(".")[0]
if tid == "nav-home" and nh:
return {"display": "block"}, None, {"display": "none"}
elif tid == "button-1" and b1:
return {"display": "none"}, html.Div("Button 1"), {"display": "block"}
elif tid == "button-2" and b2:
return {"display": "none"}, html.Div("Button 2"), {"display": "block"}
else:
raise PreventUpdate
if __name__ == "__main__":
app.run_server(debug=True, host="0.0.0.0", port=8082)