You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dash-Plotly中实现分类标题+复选框缩进文本输出?

解决Dash复选框分类显示需求

我来帮你搞定这个需求!核心逻辑很简单:只在对应分类有选中项时,才显示分类标题+选中的选项,没有选中项就彻底隐藏该分类的相关内容。

修改方案说明

  1. 把输出合并到一个统一容器(原来的两个分散输出Div可以合并,让显示更集中)
  2. 在回调函数里分别处理每个分类:
    • 检查该分类是否有选中值,有就拼接成「分类名: 选项1 选项2...」的格式
    • 没有选中值就返回空字符串,后续过滤掉这些空内容
  3. 最后把所有需要显示的分类内容用独立Div包裹,实现自然换行

修改后的完整代码

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    # 统一输出容器
    html.Div(id='output-container'),
    # 美国城市复选框
    dcc.Checklist(
        id='my-checklist1', 
        options=[
            {'label': 'New York City', 'value': 'NYC'},
            {'label': 'Montréal', 'value': 'MTL'},
            {'label': 'San Francisco', 'value': 'SF'}
        ], 
        value=[] 
    ),
    html.Hr(),
    # 欧洲城市复选框
    dcc.Checklist(
        id='my-checklist2', 
        options=[
            {'label': 'Berlin', 'value': 'BER'},
            {'label': 'Amsterdam', 'value': 'AMS'},
            {'label': 'Paris', 'value': 'PAR'}
        ], 
        value=[], 
        labelStyle={'display': 'inline-block'} 
    ),
    html.Hr(),
])

@app.callback(
    Output('output-container', 'children'),
    [Input('my-checklist1', 'value'), Input('my-checklist2', 'value') ]
)
def prepare_data(categ1, categ2):
    # 为每个分类生成显示文本,只有选中项存在时才添加分类标题
    us_section = f"US: {' '.join(categ1)}" if categ1 else ""
    europe_section = f"Europe: {' '.join(categ2)}" if categ2 else ""
    
    # 过滤掉空的分类内容,只保留需要显示的部分
    display_sections = [section for section in [us_section, europe_section] if section]
    
    # 将每个分类内容作为独立的Div元素,实现换行显示
    return html.Div([html.Div(section) for section in display_sections])

if __name__ == '__main__':
    app.run_server(debug=True)

效果验证

  • 全选所有复选框:显示 US: MTL NYC SF 和 Europe: BER AMS PAR(各占一行)
  • 不勾选任何选项:输出容器为空,无任何内容
  • 仅勾选AMS:只显示 Europe: AMS

内容的提问来源于stack exchange,提问作者Daniel Mueller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:41:09