如何在打开新Navbar Dropdownmenu时自动关闭已打开的菜单?
解决Dash导航栏下拉菜单无法自动关闭的问题
要实现打开新下拉菜单时自动关闭已打开的菜单,需要通过Dash的回调功能控制每个下拉菜单的is_open状态,具体实现如下:
修改后的完整代码
import dash from dash import html, Input, Output, State, callback, ALL import dash_bootstrap_components as dbc app = dash.Dash(external_stylesheets=[dbc.themes.DARKLY]) navbar = dbc.NavbarSimple( children=[ dbc.DropdownMenu( children=[dbc.DropdownMenuItem("How to")], nav=True, in_navbar=True, label="Here is", id={"type": "navbar-dropdown", "index": 0}, is_open=False ), dbc.DropdownMenu( children=[dbc.DropdownMenuItem("auto-close?")], nav=True, in_navbar=True, label="my question", id={"type": "navbar-dropdown", "index": 1}, is_open=False ), ], ) app.layout = html.Div([navbar]) @callback( [Output({"type": "navbar-dropdown", "index": ALL}, "is_open")], [Input({"type": "navbar-dropdown", "index": ALL}, "n_clicks")], [State({"type": "navbar-dropdown", "index": ALL}, "is_open")] ) def toggle_dropdowns(n_clicks, is_open_states): ctx = dash.callback_context if not ctx.triggered: return [is_open_states] trigger_id = ctx.triggered[0]["prop_id"].split(".")[0] trigger_index = eval(trigger_id)["index"] new_states = [] for idx, state in enumerate(is_open_states): if idx == trigger_index: new_states.append(not state) else: new_states.append(False) return [new_states] if __name__ == "__main__": app.run(host='127.0.0.1', port=80, debug=True)
关键说明
- 给每个
DropdownMenu添加动态ID(用字典格式的ID,通过type和index区分),同时初始化is_open为False。 - 使用
ALL通配符批量处理所有下拉菜单的输入输出,避免为每个菜单单独编写回调。 - 在回调中通过
callback_context获取触发点击的菜单索引,切换该菜单的状态,同时将其余菜单强制设为关闭状态。
内容的提问来源于stack exchange,提问作者Christian Karcher
相关产品推荐
相关产品推荐

