使用Dash将工具提示添加到Bootstrap表中的单元格

时间:2019-01-21 08:44:52

标签: python bootstrap-4 bootstrap-table plotly-dash twitter-bootstrap-tooltip

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

设置好我的桌子

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

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

我想使用dbc.Tooltip向我的html.td()中的项目(data_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)

1 个答案:

答案 0 :(得分:0)

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

要克服这一点,只需更改元素ID和工具提示目标即可:

str(i)+"_"+col

收件人:

col+"_"+str(i)

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

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