import dash
from dash import Dash, html, dcc
app = Dash(__name__, use_pages=True)
app.layout = html.Div([
html.H1('Multi-page app with Dash Pages'),
html.Div([
html.Div(
dcc.Link(f"{page['name']}", href=page["relative_path"])
) for page in dash.page_registry.values()
]),
dash.page_container
])
if __name__ == '__main__':
app.run(debug=True)
我想要 dcc.dropdown 而不是 dcc.link,但工作方式应该与页面名称相同,当我选择其中之一时,该页面将加载路径示例:在下拉菜单中选择水果,然后水果破折号将负载和网址如下:http://127.0.0.1:8050/fruits
import dash
from dash import dcc, html, Input, Output, Dash
app = Dash(__name__, use_pages=True)
# Convert page registry values to a list
pages_list = list(dash.page_registry.values())
# Create a dropdown for page selection
page_dropdown = dcc.Dropdown(
id="page-dropdown",
options=[{"label": page["name"], "value": page["relative_path"]} for page in pages_list],
value=pages_list[0]["relative_path"] # Set initial value to the first page
)
# Layout of the main app
app.layout = html.Div([
html.H3("Multi-Page App"),
page_dropdown, # Add the dropdown to the layout
dash.page_container
])
if __name__ == "__main__":
app.run(debug=True)
我尝试了上面的代码,但当我更改 URL 路径然后加载时,它不起作用,但当我从下拉选项中选择任何内容时,什么也没有发生。
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
app = dash.Dash(__name__, suppress_callback_exceptions=True)
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.H1('My Demo App'),
dcc.Dropdown(
id='page-dropdown',
options=[
{'label': 'Page 1', 'value': '/page-1'},
{'label': 'Page 2', 'value': '/page-2'},
],
value='/page-1'
),
html.Div(id='page-content')
])
index_page = html.Div([
html.H2('This is the index page'),
])
page_1_layout = html.Div([
html.H2('Page 1'),
])
page_2_layout = html.Div([
html.H2('Page 2'),
])
@app.callback(Output('page-content', 'children'),
[Input('url', 'pathname')])
def display_page(pathname):
if pathname == '/page-1':
return page_1_layout
elif pathname == '/page-2':
return page_2_layout
else:
return index_page
@app.callback(Output('url', 'pathname'),
[Input('page-dropdown', 'value')])
def update_url(value):
return value
if __name__ == '__main__':
app.run_server(debug=True)