更改 dbc.Table 列的文本颜色

问题描述 投票:0回答:1

我正在开发一个破折号应用程序。我有一个来自后端的数据框,在 forntend 中,我使用

dbc.Table
组件显示该数据框。

import dash_bootstrap_components as dbc
import pandas as pd

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

table = dbc.Table.from_dataframe(df, striped=True, bordered=True, hover=True)

目前,表格正在以默认文本颜色显示。我正在尝试用

 显示 
Result

Failed in Red color
Passed in Green color

这可能吗?

python pandas plotly-dash
1个回答
0
投票

条件单元格样式格式是内置的
dash.dash_table.DataTable
,并且可以自定义整体表格样式以模仿
dbc

当然可以根据您的意愿/想象更改/定制样式,但是,例如:

import pandas as pd

import dash
from dash.dash_table import DataTable

import dash_bootstrap_components as dbc

app = dash.Dash(__name__)

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

app.layout = html.Div(
    [
        DataTable(
            data=df.to_dict("records"),
            sort_action="native",
            columns=[{"name": i, "id": i} for i in df.columns],
            style_data_conditional=[
                {
                    "if": {
                        "filter_query": '{Result} = "Passed"',
                        "column_id": "Result",
                    },
                    "color": "green",
                    "fontWeight": "bold",
                },
                {
                    "if": {
                        "filter_query": '{Result} = "Failed"',
                        "column_id": "Result",
                    },
                    "color": "red",
                    "fontWeight": "bold",
                },
                {
                    "if": {"row_index": "odd"},
                    "backgroundColor": "rgba(210, 210, 220, 0.5)",
                },
            ],
            style_data={
                "color": "black",
                "backgroundColor": "white",
                "textAlign": "center",
            },
            style_header={
                "backgroundColor": "rgba(210, 210, 210, 0.65)",
                "color": "black",
                "fontWeight": "bold",
                "textAlign": "center",
            },
        )
    ]
)

app.run(debug=True)

产量:

© www.soinside.com 2019 - 2024. All rights reserved.