如何限制 Dash(plotly)中清单中选中复选框的数量?

How to limit the number of selected checkboxes in checklist in Dash(plotly)?

我的问题与this one that is how to limit selected number of checkboxes but I wanted this feature for the checklist in Dash provided by plotly. I have read the official documentation相同,但找不到任何有用的信息。

提前感谢您的帮助。

我已经回答了一个关于下拉菜单的类似问题 here。我们可以在这里使用相同的方法并进行一些调整。

两个 dcc.Dropdown component and the dcc.Checklist 组件都有一个 options 属性,允许设置是否禁用每个选项。

当达到您的选项限制时,我们可以通过禁用所有其他选项来使用它。

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.Checklist(
            id="dropdown",
            options=default_options,
        ),
    ]
)


@app.callback(
    Output("dropdown", "options"),
    Input("dropdown", "value"),
)
def update_multi_options(value):
    options = default_options
    if len(value) >= 3:
        options = [
            {
                "label": option["label"],
                "value": option["value"],
                "disabled": option["value"] not in value,
            }
            for option in options
        ]
    return options


if __name__ == "__main__":
    app.run_server()

以上示例在已选中 3 个复选框时禁用所有其他复选框。