You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dash中dbc.Button内图标不显示问题排查

Dash密码切换图标不显示的问题解决

核心问题

你代码里用了Bootstrap Icons的类名(比如bi bi-eye-fill),但加载的却是Font Awesome的图标样式表(dbc.icons.FONT_AWESOME),两者不匹配,导致图标无法渲染。

解决方法

方案1:使用Bootstrap Icons(匹配你原本的需求)

把样式表中的dbc.icons.FONT_AWESOME替换为dbc.icons.BOOTSTRAP,这样就能正确加载Bootstrap Icons的样式:

修改后的完整代码:

import dash
import dash_bootstrap_components as dbc
from dash import Output, Input, State, html
from dash.exceptions import PreventUpdate

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

app.layout = dbc.Container(
    dbc.Form(
        [
            dbc.Label("Password"),
            dbc.InputGroup(
                [
                    dbc.Input(
                        id="signup-password",
                        type="password",
                        placeholder="",
                        required=True,
                    ),
                    dbc.Button(
                        html.I(className="bi bi-eye-fill"),
                        id="password-toggle",
                        n_clicks=0,
                        outline=True,
                        color="secondary",
                        style={
                            "cursor": "pointer",
                            "display": "inline-block",
                        },
                    ),
                ],
                className="mb-3",
            ),
        ],
        className="mb-3",
    ),
    className="p-5",
)

# Callback to toggle password visibility
@app.callback(
    Output("signup-password", "type"),
    Output("password-toggle", "children"),
    Input("password-toggle", "n_clicks"),
    State("signup-password", "type"),
)
def toggle_password_visibility(n_clicks, current_type):
    if n_clicks is None:
        raise PreventUpdate
    return (
        ("password", html.I(className="bi bi-eye-fill"))
        if current_type == "text"
        else ("text", html.I(className="bi bi-eye-slash-fill"))
    )

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

方案2:改用Font Awesome图标(如果偏好这个库)

如果你想继续使用Font Awesome的样式表,需要把图标类名换成Font Awesome的对应类:

  • 显示密码:fa fa-eye
  • 隐藏密码:fa fa-eye-slash

修改后的按钮和回调部分示例:

# 按钮部分
dbc.Button(
    html.I(className="fa fa-eye"),
    id="password-toggle",
    # 其他属性不变
),

# 回调返回部分
return (
    ("password", html.I(className="fa fa-eye"))
    if current_type == "text"
    else ("text", html.I(className="fa fa-eye-slash"))
)

补充说明

你的回调逻辑是正常的,按钮切换密码显示/隐藏的功能没问题,只需要解决图标样式表和类名匹配的问题即可。

内容的提问来源于stack exchange,提问作者RedPen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 11:36:13