可以限制用户可以在Dash-Ploty组件中输入的IF值的数量
问题描述
正在尝试限制用户可以在我的多个下拉列表中输入的输入量。在下面的代码中,我将其设置为最大值4!
此代码不会带回错误,但它的运行方式与我希望的不同。我希望回调在数字超过4时阻止用户输入更多内容。
@app.callback(
[dash.dependencies.Output("input-warning", "children"),
dash.dependencies.Output("dynamic-dropdown", "options")],
[dash.dependencies.Input("dynamic-dropdown", "search_value")],
[dash.dependencies.State("dynamic-dropdown", "value")],
)
def update_multi_options(search_value, value):
conn.rollback()
if search_value is None:
raise PreventUpdate
elif len(value) >= 4:
children = html.P("limit reached",id='input-warning')
return [children, [o for o in OPTIONS if o["value"] in value]]
else:
# Make sure that the set values are in the option list, else they will disappear
# from the shown select list, but still part of the `value`.
return [
o for o in OPTIONS if search_value.upper() in o["label"].upper() or o["value"] in (value or [])
]
我设置了elif
条件以尝试限制输入,但无法使其工作。
如果能就我的代码为何无法实现我想要的效果提供一些指导,我将非常感激。
解决方案
您可以在达到最大选项数时将每个选项的disabled
键值设置为True
,以便无法再选择其余选项。当您尚未达到阈值时,您可以返回原始选项列表(已隐式启用)。
from dash import Dash, html, dcc
from dash.dependencies import Output, Input
default_options = [
{"label": "A", "value": "A"},
{"label": "B", "value": "B"},
{"label": "C", "value": "C"},
{"label": "D", "value": "D"},
{"label": "E", "value": "E"},
{"label": "F", "value": "F"},
]
app = Dash(__name__)
app.layout = html.Div(
[
dcc.Dropdown(
id="dropdown",
options=default_options,
value=["MTL", "NYC"],
multi=True,
),
html.Div(id="warning"),
]
)
@app.callback(
Output("dropdown", "options"),
Output("warning", "children"),
Input("dropdown", "value"),
)
def update_multi_options(value):
options = default_options
input_warning = None
if len(value) >= 4:
input_warning = html.P(id="warning", children="Limit reached")
options = [
{"label": option["label"], "value": option["value"], "disabled": True}
for option in options
]
return options, input_warning
if __name__ == "__main__":
app.run_server()
相关文章