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

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

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

我的 table 摆好了

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

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

我想使用 dbc.Tooltipdata_table 中的项目(html.td() 元素)添加工具提示>。我的第一个想法是为表中的每个元素分配一个与其位置相对应的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

关于python - 使用 Dash 将工具提示添加到 Bootstrap Table 中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54286143/

相关文章:

python - CSS 选择器无法识别数字

python - 如何将格式字符串中的千位分隔符更改为撇号

css - Kendo 对话框未扩展到 bootstrap 4 表单组的宽度

javascript - Bootstrap-Table 插件,按初始搜索值过滤

python相当于perl的qw()

python - 在 Django 中保存或显示表单数据的最简单方法

css - 如何滚动 flex-grow-1 的 flex 行的内容

css - 带有顶部导航的可折叠侧边栏

javascript - 如何根据引导表的内容更改引导表行背景

html - bootstrap-table 更改由 bootstrap 设置的布局