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

如何为Dash框架中dbc.Table的Result列设置差异化文本颜色?

实现Result列内容按条件设置颜色

完全可以实现这个需求,下面提供两种实用的实现方式:

方法一:手动构建表格并设置单元格样式

直接遍历DataFrame的行和列,针对Result列的内容判断后给单元格添加颜色样式:

import dash_bootstrap_components as dbc
import pandas as pd
from dash import html

df = pd.DataFrame(
    {
        "First Name": ["Arthur", "Ford", "Zaphod", "Trillian"],
        "Last Name": ["Dent", "Prefect", "Beeblebrox", "Astra"],
        "Result": ["Failed", "Passed", "Passed", "Failed"],
    }
)

# 生成表头
header = [html.Thead(html.Tr([html.Th(col) for col in df.columns]))]

# 生成表格主体行
table_rows = []
for _, row in df.iterrows():
    row_cells = []
    for col_name, cell_value in row.items():
        if col_name == "Result":
            # 根据结果设置文本颜色
            text_color = "red" if cell_value == "Failed" else "green"
            row_cells.append(html.Td(cell_value, style={"color": text_color}))
        else:
            row_cells.append(html.Td(cell_value))
    table_rows.append(html.Tr(row_cells))
body = [html.Tbody(table_rows)]

# 创建带样式的dbc.Table组件
styled_table = dbc.Table(
    header + body,
    striped=True,
    bordered=True,
    hover=True
)

方法二:通过CSS类管理样式(更易维护)

如果需要统一管理样式,推荐使用CSS类来定义颜色,避免在Python代码中硬写样式:

  1. 在Dash项目的assets文件夹下创建styles.css文件,添加如下样式:
.failed-result {
    color: red;
}
.passed-result {
    color: green;
}
  1. 在Python代码中给对应单元格添加类名:
import dash_bootstrap_components as dbc
import pandas as pd
from dash import html

df = pd.DataFrame(
    {
        "First Name": ["Arthur", "Ford", "Zaphod", "Trillian"],
        "Last Name": ["Dent", "Prefect", "Beeblebrox", "Astra"],
        "Result": ["Failed", "Passed", "Passed", "Failed"],
    }
)

header = [html.Thead(html.Tr([html.Th(col) for col in df.columns]))]
table_rows = []
for _, row in df.iterrows():
    row_cells = []
    for col_name, cell_value in row.items():
        if col_name == "Result":
            # 根据结果选择CSS类
            cell_class = "failed-result" if cell_value == "Failed" else "passed-result"
            row_cells.append(html.Td(cell_value, className=cell_class))
        else:
            row_cells.append(html.Td(cell_value))
    table_rows.append(html.Tr(row_cells))
body = [html.Tbody(table_rows)]

styled_table = dbc.Table(
    header + body,
    striped=True,
    bordered=True,
    hover=True
)

这两种方法都能实现你要的效果,方法二更适合后续样式的调整和扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:03:30