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

如何在Jupyter Notebook中显示带JavaScript交互的SVG图像

解决Jupyter Notebook中SVG交互失效的问题

问题根源在于Jupyter自带的SVG组件会出于安全考量,自动移除SVG文件中的<script>标签,导致你的点击变色逻辑根本没被加载执行。

下面是两种可行的解决方案:

方案一:用HTML组件渲染SVG(推荐)

改用IPython.display.HTML来渲染SVG内容,HTML渲染器不会过滤脚本标签,能完整保留交互逻辑:

from IPython.display import HTML, display

# 读取本地SVG文件
with open('interactive.svg', 'r') as f:
    svg_content = f.read()

# 用HTML组件展示
display(HTML(svg_content))

如果不想依赖本地文件,也可以直接把SVG代码内嵌到代码中:

from IPython.display import HTML, display

svg_code = '''<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100">
  <script type="text/ecmascript">
    //<![CDATA[
      function changeColor() {
        const el = document.getElementById("box");
        el.setAttribute("style", "fill: red; stroke: black;");
      }
    //]]>
  </script>
  <rect style="fill: white; stroke: black;" height="100" x="0" y="0" width="100" onclick="changeColor()" id="box" />
</svg>'''

display(HTML(svg_code))

注:把函数名从click改为changeColor是避免和DOM原生的click事件冲突,减少潜在问题。

方案二:使用内联事件处理(适合简单逻辑)

如果你的交互逻辑很简单,可以直接把代码写在onclick属性里,不用单独的<script>标签,这样即使SVG组件过滤脚本,逻辑依然能执行:

修改后的SVG代码:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100">
  <rect style="fill: white; stroke: black;" height="100" x="0" y="0" width="100" onclick="this.setAttribute('style', 'fill: red; stroke: black;')" id="box" />
</svg>

之后依然可以用原来的display(SVG('interactive.svg'))来展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:15:01