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

如何在Plotly Dash中打开新标签页?附代码求助

解决方案:点击按钮打开新标签页显示"Hello"

给你两种可行的实现方式,按需选择即可:

方案一:跳转至独立页面

这种方式需要给Dash添加一个新路由页面,用链接包裹按钮实现新标签页打开:

from dash import Dash, html

app = Dash(__name__)

# 主页面布局
app.layout = html.Div([
    # 用A标签包裹按钮,设置跳转地址和新标签页打开属性
    html.A(
        html.Button("Press", id="newpage"),
        href="/hello-page",
        target="_blank"
    )
])

# 注册新路由,返回显示Hello的HTML内容
@app.server.route('/hello-page')
def show_hello():
    return "<html><body><h1>Hello</h1></body></html>"

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

点击按钮后,会在新标签页打开/hello-page路由对应的页面,直接显示Hello。

方案二:用前端JS直接生成新窗口内容

不想额外添加路由的话,用客户端回调编写JS逻辑,直接在新窗口中写入内容:

from dash import Dash, html, clientside_callback, Input, Output

app = Dash(__name__)

app.layout = html.Div([
    html.Button("Press", id="newpage")
])

# 客户端回调,在浏览器端执行JS代码
clientside_callback(
    """
    function(n_clicks) {
        if (n_clicks) {
            // 打开新标签页
            const newWindow = window.open('', '_blank');
            // 写入Hello的HTML内容
            newWindow.document.write('<html><body><h1>Hello</h1></body></html>');
            newWindow.document.close();
        }
        return null;
    }
    """,
    Output("newpage", "n_clicks"),  # 指定一个无影响的输出属性即可
    Input("newpage", "n_clicks")
)

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

这个方案不需要后端额外配置路由,点击按钮后直接在前端生成新窗口并显示Hello。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:01:10