gpt4 book ai didi

python - 自动选择复选框 Python 和 Dash

转载 作者:行者123 更新时间:2023-12-05 05:55:34 26 4
gpt4 key购买 nike

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

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

谢谢!我使用了 Google 协作

!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')

最佳答案

一种方法是将您的 my-checklist 选项放在一个变量中,并将该变量传递给 my-checklistoptions 属性:

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

然后你可以检查从my-checklist中选择的选项的数量是否等于回调中的all_options的长度来判断是否所有选项都被选中。

此外,每次选择 my-checklist 的选项时,您都需要进行检查,以便切换 Select All 复选框。

例如:

@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

我在这里 dash.callback_context 确定哪个 Input 触发了回调。有关 dash.callback_context 的更多信息,请参阅文档 here .

关于python - 自动选择复选框 Python 和 Dash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69457378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com