python - 自动选择复选框 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')
解决方案
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.
推荐阅读
- ios - 如何在 swift 4 中使用 UIImagePickerController
- javascript - 使用 P-Queue 节点模块排队 Promise
- wordpress - 与文本重叠的重力形式单选按钮
- redirect - NGINX 强制 www 和 https 导致重定向过多
- git - 查看更新的 git 裸存储库文件的最佳方式是什么?(ls-tree 的概念)
- c# - 尝试在 asp.net mvc 中注册用户时出错
- java - 我可以将哪种类型的参数传递给 JAVA 8 中的 ToIntFunction 功能接口
- python - Python函数意外输出
- xamarin - 错误 MT2001:无法链接程序集。原因:处理引用时出错
- json - 使用 JavaScript React Native 从 API 的 json 对象中提取数据