简体   繁体   中英

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

My question is the same as 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 but can't find anything useful.

Thanks for the help in advance.

I've answered a similar question for dropdowns here . We can use the same approach here with some adjustments.

Both the dcc.Dropdown component and the dcc.Checklist component have an options prop that allows setting whether each option is disabled or not.

We can use this by disabling all other options when your option limit has been reached.

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()

The above example disables all other checkbox when 3 checkboxes have already been selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM