使用破折号向 Bootstrap Table 中的单元格添加工具提示

Adding a tooltip to a cell in a Bootstrap Table using Dash

我正在使用 Dash 构建一个应用程序,该应用程序的一部分正在显示数据 table。我使用 dash-bootstrap-components 中的 Table() 函数将 table 从 pandas 数据帧转换为 Dash 中的 Bootstrap Table。

用我的 table 设置

import dash-bootstrap-components as dbc
import dash_html_components as html
import dash

data_table = dbc.Table(# code to construct table)

我想使用 dbc.Tooltip 向我的 data_table 中的项目(html.td() 元素)添加工具提示。我的第一个想法是为 table 中的每个元素分配一个与其位置相对应的 id,然后附加一个工具提示

tooltip = dbc.Tooltip("Tooltip text", target = id)

然后我们把它们放在一起。

app = dash.Dash(_name_)
app.layout = html.Div(
                 children = [data_table, tooltip]
             )

然而,这似乎并没有奏效,我正在为如何从理论上实现这一点而苦苦挣扎,找不到太多帮助。

更新:

这是我正在尝试做的一些示例代码。它给出了一个错误,如果你删除分段注释 "REMOVE TO WORK" 代码将起作用。

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd


app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

data = {
            "Name" : ["Tom", "Jack", "Jill", "Jane"],
            "Age"  : [21, 30, 45, 80]
        }
fixt_df = pd.DataFrame.from_dict(data)

#Setup table
table = dbc.Table(
            # Header
            [html.Thead([html.Tr([html.Th(col) for col in fixt_df.columns])])] +

            # Body
            [html.Tbody([html.Tr([html.Td(html.A(fixt_df.iloc[i][col], id = ""+str(i)+"_" + col))
                for col in fixt_df.columns])
                for i in range(len(fixt_df))])]
            ,
            hover = True,
            className = "table-responsive table-hover"
        )

items = [table]
# REMOVE TO WORK
for col in fixt_df.columns:
    for i in range(len(fixt_df)):
        items.extend([dbc.Tooltip("test", target = str(i)+"_"+col)])
# REMOVE TO WORK
app.layout = html.Div(
                children = [
                    #header
                    html.Div(
                        html.H1("Example")
                    ),
                    #table
                    html.Div(
                        items
                    )
                ]
            )

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

我发现了你的问题 - 由于某些原因,dbc.Tooltip 元素不能很好地与 ID 以数字开头的元素一起使用。

为了克服这个问题,在元素 ID 和工具提示目标中只需更改:

str(i)+"_"+col

至:

col+"_"+str(i)

或者,您可以添加字母前缀:

"p_"+str(i)+"_"+col