如何在 Dash 中禁用的切换按钮上显示悬停消息?

问题描述 投票:0回答:1

我正在开发一个 Dash 应用程序,其中有一个切换按钮 (

dbc.Switch
),该按钮根据用户的输入被禁用。我想在禁用切换按钮时显示悬停工具提示消息。但是,我注意到当按钮被禁用时,工具提示不会出现。这是我正在使用的代码:

import dash_bootstrap_components as dbc
from dash import Dash, html, dcc, Input, Output

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

app.layout = html.Div(
    [
        dcc.Input(id='number-input', type='number', placeholder='Enter a number'),
        dbc.Switch(
            id="toggle-button",
            label="Toggle Button",
            style={"display": "inline-block", "margin-right": "10px"}
        ),
        dbc.Tooltip(
            id="toggle-tooltip",
            target="toggle-button",
            placement="top"
        ),
    ]
)

@app.callback(
    Output("toggle-button", "disabled"),
    Output("toggle-tooltip", "children"),
    Input("number-input", "value")
)
def update_toggle(number):
    if number is not None and number % 2 == 0:
        return False, "Disabled for even numbers"
    else:
        return True, "This is a toggle button"

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

当输入数字为偶数时,

toggle-button
会被禁用,我希望
toggle-tooltip
显示一条消息,解释为什么它被禁用,当我将鼠标悬停在切换上时,应该会出现该消息。将鼠标悬停在禁用按钮上时,工具提示应该仍然可见。

python plotly-dash
1个回答
0
投票

在 Dash 中,禁用组件上的工具提示不会出现,因为工具提示通常与组件禁用时不可能进行的用户交互相关联。您可以使用自定义 CSS 创建可见的工具提示或覆盖层,可以在禁用按钮时显示。

import dash_bootstrap_components as dbc
from dash import Dash, html, dcc, Input, Output

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

app.layout = html.Div(
    [
        dcc.Input(id='number-input', type='number', placeholder='Input number'),
        html.Div(
            [
                dbc.Switch(
                    id="toggle-button",
                    label="Toggle button",
                    style={"display": "inline-block", "margin-right": "10px"}
                ),
                html.Span(
                    id="toggle-tooltip",
                    children="",
                    style={"visibility": "hidden", "position": "absolute", "backgroundColor": "lightgray", "border": "1px solid black", "padding": "5px"}
                )
            ],
            style={"position": "relative"}
        ),
    ]
)

@app.callback(
    Output("toggle-button", "disabled"),
    Output("toggle-tooltip", "children"),
    Output("toggle-tooltip", "style"),
    Input("number-input", "value")
)
def update_toggle(number):
    if number is not None and number % 2 == 0:
        return True, "Disabled due to input being an even number", {"visibility": "visible", "position": "absolute", "top": "20px", "left": "0px"}
    else:
        return False, "A toggle button", {"visibility": "hidden"}

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

© www.soinside.com 2019 - 2024. All rights reserved.