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

在HTML的<py-script>中导入matplotlib失败(HTML新手求助)

解决PyScript中导入matplotlib的ModuleNotFoundError问题

问题原因

你遇到的ModuleNotFoundError: No module named 'matplotlib',是因为PyScript基于Pyodide运行,默认环境并未预装matplotlib这类第三方库,必须手动声明依赖并加载。

解决步骤

在HTML的<head>标签内添加<py-env>标签,明确指定需要安装的matplotlib包:

<py-env>
  - matplotlib
</py-env>

修改后的完整代码

<!DOCTYPE html>
<html>
  <head>
    <title>Cellular Automata</title>
    <style>
      .footnote{
        font-family:Gill Sans;
        color:darkslategrey;
      }
      .citations{
        position:relative;
        overflow:auto;
        background-color:antiquewhite;
        border:5px antiquewhite;
        padding:40px;
      }
    </style>
    <meta charset="utf-8" />  
    <meta name="viewport" content="width=device-width, initial-scale=1" />  
    <title>Hello World!</title>  
    <!-- linking to PyScript assets -->  
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />  
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <!-- 声明Python依赖 -->
    <py-env>
      - matplotlib
    </py-env>  
  </head>
  <body style="margin: 0;">
    <div class="citations">
      <p class="footnote"id = "footnote-1">[1] My footnote!</p>
      <py-script>
        #06/2023
        from matplotlib import pyplot as plt
        print(2)
        # 可选:添加简单绘图测试
        plt.plot([1,2,3], [4,5,6])
        display(plt)
      </py-script>
    </div>
  </body>
</html>

补充说明

PyScript通过<py-env>管理Python依赖,启动时会自动从Pyodide的包仓库下载并安装指定库,确保代码运行时能找到对应的模块。如果需要多个第三方包,只需在<py-env>内逐行添加即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:17:39