首页 > 解决方案 > 使用 dash python 更改 boostrap nav-pills 样式

问题描述

Dash 允许使用我们自己的 CSS 样式表。但是,如果您在科学领域并且不熟悉 CSS,则可以使用 Bootstrap 组件,这使得样式和页面布局非常容易组合在一起。

这是创建侧边栏的标准示例:"""

This app creates a simple sidebar layout using inline style arguments and the
dbc.Nav component.
dcc.Location is used to track the current location. There are two callbacks,
one uses the current location to render the appropriate page content, the other
uses the current location to toggle the "active" properties of the navigation
links.
For more details on building multi-page Dash applications, check out the Dash
documentation: https://dash.plot.ly/urls
"""
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

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

# the style arguments for the sidebar. We use position:fixed and a fixed width
SIDEBAR_STYLE = {
    "position": "fixed",
    "top": 0,
    "left": 0,
    "bottom": 0,
    "width": "16rem",
    "padding": "2rem 1rem",
    "background-color": "#f8f9fa",
}

# the styles for the main content position it to the right of the sidebar and
# add some padding.
CONTENT_STYLE = {
    "margin-left": "18rem",
    "margin-right": "2rem",
    "padding": "2rem 1rem",
}

sidebar = html.Div(
    [
        html.H2("Sidebar", className="display-4"),
        html.Hr(),
        html.P(
            "A simple sidebar layout with navigation links", className="lead"
        ),
        dbc.Nav(
            [
                dbc.NavLink("Page 1", href="/page-1", id="page-1-link"),
                dbc.NavLink("Page 2", href="/page-2", id="page-2-link"),
                dbc.NavLink("Page 3", href="/page-3", id="page-3-link"),
            ],
            vertical=True,
            pills=True,
        ),
    ],
    style=SIDEBAR_STYLE,
)

content = html.Div(id="page-content", style=CONTENT_STYLE)

app.layout = html.Div([dcc.Location(id="url"), sidebar, content])


# this callback uses the current pathname to set the active state of the
# corresponding nav link to true, allowing users to tell see page they are on
@app.callback(
    [Output(f"page-{i}-link", "active") for i in range(1, 4)],
    [Input("url", "pathname")],
)
def toggle_active_links(pathname):
    if pathname == "/":
        # Treat page 1 as the homepage / index
        return True, False, False
    return [pathname == f"/page-{i}" for i in range(1, 4)]


@app.callback(Output("page-content", "children"), [Input("url", "pathname")])
def render_page_content(pathname):
    if pathname in ["/", "/page-1"]:
        return html.P("This is the content of page 1!")
    elif pathname == "/page-2":
        return html.P("This is the content of page 2. Yay!")
    elif pathname == "/page-3":
        return html.P("Oh cool, this is page 3!")
    # If the user tries to reach a different page, return a 404 message
    return dbc.Jumbotron(
        [
            html.H1("404: Not found", className="text-danger"),
            html.Hr(),
            html.P(f"The pathname {pathname} was not recognised..."),
        ]
    )


if __name__ == "__main__":
    app.run_server(port=8888)

Bootstrap 导航丸是导航栏中的元素。它们是导航组件,允许用户浏览布局中的各种选项。例子

在 CSS 脚本示例中,药丸具有不同的组件,可以是样式,例如:

/* CSS used here will be applied after bootstrap.css */
body {
  background: #000;
}
.nav-pills a {
    color: #ffffff
}

.nav-pills a:hover {
    color: #560000;
    border-radius: 0px;
}

.nav-pills .active a:hover {
    color: #560000;
    border-radius: 0px;
}
.nav>li>a:hover, 
.nav>li>a:focus {
    color: #560000;
    border-radius: 0px;
}

我想通过我的python脚本更新药丸样式,并在悬停时更改药丸的颜色,当我想更改字体类型和文本颜色时。我仍然熟悉 CSS,因此我宁愿通过 python 脚本更新它。通过设置样式参数,我确实成功地覆盖了 CSS 样式。

根据 Dash Bootstrap 组件,我可以将药丸设置为导航项目,如下所述:

药丸(布尔值,可选):将药丸样式应用于导航项目。活动项目将由药丸指示。

我已经编辑了这样的代码:

sidebar = html.Div(
    [
        html.H2("Sidebar", className="display-4"),
        html.Hr(),
        html.P(
            "A simple sidebar layout with navigation links", className="lead"
        ),
        dbc.Nav(
            [
                dbc.NavItem(dbc.NavLink("Page 1", href="/page-1", id="page-1-link"), style={"background-color": "grey"}),
                dbc.NavLink("Page 2", href="/page-2", id="page-2-link"),
                dbc.NavLink("Page 3", href="/page-3", id="page-3-link"),
            ],
            vertical=True,
            pills=True,

           # className="nav navbar-nav",#"nav nav-pills hidden-sm",
            #style ={"li:hover" =""}

        ),
    ],
    style=SIDEBAR_STYLE,
)

侧边栏

这只会在悬停或活动时更改背景颜色而不是药丸颜色和字体颜色。python中的语法是什么?我在代码中尝试了许多选项,并且在 python 中搜索了样式语法,但我仍然没有遇到等效的 python 样式语法示例

我最接近更改药丸样式的方法是更改​​可用的引导样式表:

app = dash.Dash(external_stylesheets=[dbc.themes.FLATLY])

扁平引导主题

您可以在此处查看各种主题及其 html 代码

标签: plotly-dash

解决方案


我强烈建议您采用在您的 css 样式表中处理伪类样式的方法:hover:active

如需包含 css 样式表,请参阅此处的文档。基本上,您只需要assets在根目录中创建一个文件夹并将.css文件放入其中。

因此,您可以className为 each 添加一个属性NavLink,使用样式表中的类定位元素,并根据需要添加:hover:active样式。

在 Dash 布局中:

dbc.NavLink("Page 1", href="/page-1", id="page-1-link", className="page-link"),

在您的assets目录中的 css 文件中:

.page-link:hover {
  background-color: green;
}

.page-link:active {
  background-color: blue;
}

您还可以在文件夹中包含脚本assets并使用 Javascript 设置元素的样式,如果您需要以 css 无法实现的方式使其成为动态元素。

为什么你的方法不能以你期望的方式使用内联样式,请参阅CSS Pseudo-classes with inline styles

现在可以Location用来监听路由变化,并NavLink根据当前路由改变每个路由的活动状态。我再次推荐更简单且更易于扩展的 css 方法,以下方法也不适用于悬停,但您可以执行以下操作来更改单击时的样式:

from dash import Dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

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

links = [
    {"id": "page-1-link", "href": "/page-1", "link-text": "Page 1"},
    {"id": "page-2-link", "href": "/page-2", "link-text": "Page 2"},
    {"id": "page-3-link", "href": "/page-3", "link-text": "Page 3"},
]

sidebar = html.Div(
    [
        dcc.Location(id="url", refresh=False),
        html.H2("Sidebar", className="display-4"),
        html.Hr(),
        html.P("A simple sidebar layout with navigation links", className="lead"),
        dbc.Nav(
            [
                dbc.NavItem(
                    dbc.NavLink(link["link-text"], href=link["href"], id=link["id"])
                )
                for link in links
            ],
            vertical=True,
            pills=True,
        ),
    ],
)

app.layout = sidebar


@app.callback(
    [Output(link["id"], "active") for link in links],
    Input("url", "pathname"),
    prevent_initial_call=True,
)
def display_page(pathname):
    actives_list = [False for link in links]

    if pathname == "/":
        return actives_list

    actives_list[int(pathname[-1]) - 1] = True

    return actives_list


if __name__ == "__main__":
    app.run_server(port=8888)

推荐阅读