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

如何在Dash中将Cytoscape组件的节点设置为可点击跳转的超链接?

实现方案

该功能可以正常实现,核心通过监听Dash Cytoscape的节点点击事件配合跳转组件完成,具体修改方式如下:

修改步骤

  • 给每个节点的data属性新增url自定义字段,存储对应节点的跳转目标地址
  • 在布局中添加dcc.Location组件,用于控制浏览器地址跳转
  • 新增回调函数,监听节点点击事件,触发后将对应地址赋值给跳转组件

完整修改后代码

import dash
import dash_core_components as dcc
from dash import html
import dash_cytoscape as cyto
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
    # 新增跳转控制组件
    dcc.Location(id='location', refresh=True),
    html.P("Dash Cytoscape:"),
    cyto.Cytoscape(
        id='cytoscape',
        # 每个节点新增url字段存储目标地址
        elements=[
            {'data': {'id': 'ca', 'label': 'Canada', 'url': 'https://zh.wikipedia.org/wiki/加拿大'}}, 
            {'data': {'id': 'on', 'label': 'Ontario', 'url': 'https://zh.wikipedia.org/wiki/安大略省'}}, 
            {'data': {'id': 'qc', 'label': 'Quebec', 'url': 'https://zh.wikipedia.org/wiki/魁北克省'}},
            {'data': {'source': 'ca', 'target': 'on'}}, 
            {'data': {'source': 'ca', 'target': 'qc'}}
        ],
        layout={'name': 'breadthfirst'},
        style={'width': '1000px', 'height': '1000px'}
    )
])

# 新增点击跳转回调
@app.callback(
    Output('location', 'href'),
    Input('cytoscape', 'tapNodeData')
)
def navigate_to_url(node_data):
    # 只有点击节点时才触发跳转
    if node_data:
        return node_data['url']
    # 未点击节点时不跳转
    return dash.no_update

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

补充说明

如果需要点击后在新标签页打开链接,不需要替换当前应用页面,可以使用客户端回调调用浏览器原生的window.open方法实现,不需要修改原有业务逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:06:03