【发布时间】:2021-12-11 19:26:29
【问题描述】:
我正在尝试根据滑块的输入在 Plotly Dash 中输出特定数量的复选框。目的是用户从下拉框中选择某个变量并从滑块中选择一个值,然后返回特定数量的复选框(基于滑块)显示变量的值。
目前代码对一个复选框工作正常,但我似乎无法找到一种方法来循环遍历 div 中的组件列表,当我输出多个复选框时,我收到一个回调错误,说明预期长度为 1 并获得了更大的值。
我当前的代码是:
import pandas as pd
import dash # (version 2.0.0) pip install dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
app = dash.Dash(__name__)
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
df = pd.DataFrame({'CharName': ['VAR1', 'VAR1', 'VAR1', 'VAR1', 'VAR1', 'VAR1', 'VAR1', 'VAR1', 'VAR1', 'VAR1', 'VAR1',
'VAR2', 'VAR2', 'VAR3', 'VAR3'], 'CharValues': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'N',
'Y', 'N', 'Y']})
chars_list = [{'label': char, 'value': char} for char in df['CharName'].unique()]
# -------------------------------------------------------------------------------------------------------
# APP LAYOUT
app.layout = html.Div(children=[
html.H1(
children='PLOTLY DASH',
style={
'textAlign': 'center',
'color': colors['text']
}
),
dcc.Dropdown(id="select_char",
options=chars_list,
multi=False,
value=df['CharName'].unique()[0],
style={'width': "40%"}
),
html.Br(),
dcc.Slider(
id='bin_no',
min=1,
max=7,
step=1,
value=3,
marks={n: str(n) for n in range(1, 8)}
),
html.Br(),
html.Div(id="bins", children=[]),
])
@app.callback(
[Output(component_id='bins', component_property='children')],
[Input(component_id='bin_no', component_property='value'),
Input(component_id='select_char', component_property='value')]
)
def set_checkboxes(bin_no, select_char):
dff = df.copy()
dff = dff[dff["CharName"] == select_char]
value_list = [{'label': value, 'value': value} for value in dff["CharValues"].dropna()]
checklist_list = []
for i in range(bin_no):
checklist_list.append(
dcc.Checklist(
id=f'bin_{i}',
options=value_list
)
)
# return checklist_list
return dcc.Checklist(
id='bin_one',
options=value_list
),
if __name__ == '__main__':
app.run_server(debug=True)
提前谢谢你!
解决方案:
@app.callback(
Output(component_id='bins', component_property='children'),
[Input(component_id='bin_no', component_property='value'),
Input(component_id='select_char', component_property='value')],
State('bins', 'children')
)
def set_checkboxes(bin_no, select_char, children):
dff = df.copy()
dff = dff[dff["CharName"] == select_char]
# Null dropped for now due to error with no label or value
value_list = [{'label': value, 'value': value} for value in dff["CharValues"].dropna()]
checklist = []
for i in range(bin_no):
checklist.append(
dcc.Checklist(
id={'index': i},
options=value_list
)
)
return checklist
【问题讨论】:
-
我无法重现您提到的错误。您可以为此用例使用模式匹配回调。
-
@snehilvj - 你好,我注释掉了底部的'return checklist_list'语句,但是如果你取消注释并注释掉下面的return语句,就会出现错误消息。谢谢:)
标签: python plotly-dash