dash core component下拉列表和dash bootstrap组件背后的逻辑有点不同,我希望两者兼得:dbc的漂亮风格和dcc的功能。然而,修改dcc的css使其看起来更漂亮是很复杂的,我找不到现有的解决方案。设置dbc组件需要一些设置工作,因为下拉列表中的每个元素都有自己的id。此外,如果您想直接从下拉列表中获取所选值(如果您询问下拉列表实际显示的内容),则无法直接进行设置
因此,我想设置一个函数来自动设置下拉菜单和它的回调,但我遇到了一个问题,即回调是一个嵌套函数,因此不能全局使用。我怎样才能改变这一点?或者有没有其他方法来建造它
最后我想要的是一种简单的方法来设置dbc下拉列表,以便它显示所选的值。 这就是我目前所拥有的(不起作用的解决方案):
import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
def selectable_dropdown(item_id="dropdown",
options=['option_1','option_2']):
# create the items and the ids for each item
dropdown_items = [dbc.DropdownMenuItem(item, id=item_id+'_'+item)
for item in options]
# create the dropdown menu
dropdown = dbc.DropdownMenu(
dropdown_items,
label="none",
addon_type="prepend",
bs_size="sm",
id=item_id
)
output = Output(item_id, "label")
inputs = [Input(item_id+'_'+item, "n_clicks") for item in options]
@app.callback(output,inputs)
def update_label(*args):
# get the triggered item
ctx = dash.callback_context
triggered_id = ctx.triggered[0]["prop_id"].split(".")[0]
# get the label for the triggered id or return no selection
if (np.array([n==None for n in args]).all()) or not ctx.triggered:
return "no selection"
else:
return [label for label in options if item_id+'_'+label == triggered_id]
return dropdown
app = dash.Dash(
external_stylesheets=[dbc.themes.BOOTSTRAP]
)
app.config['suppress_callback_exceptions'] = True
app.layout = \
html.Div([selectable_dropdown(item_id="target_select",
options=["option1 ", "option 2", "option3"])])
if __name__ == "__main__":
app.run_server(debug=False, host = '0.0.0.0', port = 1234)
这就是它应该看起来的样子(一个工作示例),但我以一种更一般化的方式,并以最好的方式,仅在一个函数或类中:
import dash
import numpy as np
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
options=["option1 ", "option 2", "option3"]
item_id = 'dropdown'
dropdown_items = [dbc.DropdownMenuItem(item, id=item_id+'_'+item)
for item in options]
# create the dropdown menu
dropdown = dbc.DropdownMenu(
dropdown_items,
label="none",
addon_type="prepend",
bs_size="sm",
id=item_id)
output = Output(item_id, "label")
inputs = [Input(item_id+'_'+item, "n_clicks") for item in options]
app = dash.Dash(
external_stylesheets=[dbc.themes.BOOTSTRAP,'./assets/stylesheet.css']
)
app.config['suppress_callback_exceptions'] = True
app.layout = \
html.Div([dropdown])
@app.callback(output,inputs)
def update_label(*args):
# get the triggered item
ctx = dash.callback_context
triggered_id = ctx.triggered[0]["prop_id"].split(".")[0]
# get the label for the triggered id or return no selection
if (np.array([n==None for n in args]).all()) or not ctx.triggered:
return "no selection"
else:
return [label for label in options if item_id+'_'+label == triggered_id]
if __name__ == "__main__":
app.run_server(debug=False, host = '0.0.0.0', port = 1234)
目前没有回答
相关问题 更多 >
编程相关推荐