首页 > 解决方案 > 自动选择复选框 Python 和 Dash

问题描述

我有这个 python 代码工作 - 如果用户选择“全选”复选框,则所有复选框都被选中/取消选中。

如果选中/取消选中所有复选框,我需要代码自动选中/取消选中“全选”复选框。

谢谢!我使用了谷歌协作

!pip install jupyter-dash

import plotly.express as px
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from dash.dependencies import Input, Output, State



# Build App
app = JupyterDash(__name__)
app.layout = html.Div(
    [
        dcc.Checklist(
            id="all-or-none",
            options=[{"label": "Select All", "value": "All"}],
            value=[],
            labelStyle={"display": "inline-block"},
        ),
        dcc.Checklist(
            id="my-checklist",
            options=[
                {"label": "New York City", "value": "NYC"},
                {"label": "Montréal", "value": "MTL"},
                {"label": "San Francisco", "value": "SF"},
            ],
            value=[],
            labelStyle={"display": "inline-block"},
        ),
    ]
)



@app.callback(
    Output("my-checklist", "value"),
    [Input("all-or-none", "value")],
    [State("my-checklist", "options")],
)
def select_all_none(all_selected, options):
    all_or_none = []
    all_or_none = [option["value"] for option in options if all_selected]
    return all_or_none



# Run app and display result inline in the notebook
app.run_server(mode='inline')

标签: pythoncheckboxplotlyplotly-dash

解决方案


One approach could be to put your my-checklist options inside a variable and pass this variable to the options property of my-checklist:

all_options=[
    {"label": "New York City", "value": "NYC"},
    {"label": "Montréal", "value": "MTL"},
    {"label": "San Francisco", "value": "SF"},
]

Then you can check whether the number of selected options from my-checklist is equal to the length of all_options in your callback to determine if all options are selected.

Aditionally you need to check each time an option of my-checklist is selected in order to toggle the Select All checkbox.

For example:

@app.callback(
    Output("my-checklist", "value"),
    Output("all-or-none", "value"),
    Input("all-or-none", "value"),
    Input("my-checklist", "value"),
    prevent_initial_call=True,
)
def select_all_none(all_selected, options):
    ctx = dash.callback_context
    triggerer_id = ctx.triggered[0]["prop_id"].split(".")[0]

    my_checklist_options = []
    all_or_none_options = []

    if triggerer_id == "all-or-none":
        if all_selected:
            all_or_none_options = ["All"]
            my_checklist_options = [option["value"] for option in all_options]
    else:
        if len(options) == len(all_options):
            all_or_none_options = ["All"]

        my_checklist_options = options

    return my_checklist_options, all_or_none_options

I've dash.callback_context here to determine which Input triggered the callback. For more info on dash.callback_context see the documentation here.


推荐阅读