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

如何在HTML中调用PyScript函数?按钮触发函数报错求助

问题排查与解决方案

错误原因分析

  • 未导入Element类:代码中使用Element()获取DOM元素,但未从pyscript模块导入该类,导致运行时找不到对象。
  • 输入值类型错误:HTML输入框的value属性返回字符串,直接进行除法运算会触发类型错误,需转换为浮点数。
  • 旧图表未清除:多次点击按钮会重复绘制图表,导致画布内容叠加,需要在绘图前清空画布。
  • py-env注释格式错误:PyScript的环境配置中注释应使用Python的#,而非JS的//。
  • DOM标签未闭合:页面中的<div>标签未正确闭合,可能引发布局或DOM查询异常。
  • 图表标签未更新:保留了示例中的Year、Population等无关文本,不符合欧姆定律的需求。

修正后的完整代码

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>STEM projekat</title>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>

    <py-env>
        - matplotlib
        # 注释使用Python格式
    </py-env>

</head>

<body>
  <div>Napon 1</div>
  <input type="number" id="napon1" step="0.1" />

  <div>Napon 2</div>
  <input type="number" id="napon2" step="0.1" />

  <div>Napon 3</div>
  <input type="number" id="napon3" step="0.1" />

  <div>Jačina 1</div>
  <input type="number" id="jacina1" step="0.01" />

  <div>Jačina 2</div>
  <input type="number" id="jacina2" step="0.01" />

  <div>Jačina 3</div>
  <input type="number" id="jacina3" step="0.01" />

  <button type="button" id="button">OK</button>

  <!-- 用于放置图表的容器 -->
  <div id="chart-container"></div>

    <py-script> 
print("loading...")
import matplotlib.pyplot as plt
from js import document 
from pyodide import create_proxy
from pyscript import Element  # 导入Element类


def runPython():
    print("HI")
    # 获取输入值并转换为浮点数
    try:
        napon1 = float(Element('napon1').element.value)
        napon2 = float(Element('napon2').element.value)
        napon3 = float(Element('napon3').element.value)
        jacina1 = float(Element('jacina1').element.value)
        jacina2 = float(Element('jacina2').element.value)
        jacina3 = float(Element('jacina3').element.value)
    except ValueError:
        print("Molimo unesite validne brojeve!")
        return

    # 计算电阻
    otpor1 = napon1 / jacina1
    otpor2 = napon2 / jacina2
    otpor3 = napon3 / jacina3
    prosjecni_otpor = (otpor1 + otpor2 + otpor3) / 3

    # 清空之前的图表
    plt.clf()
    fig, ax = plt.subplots()
    
    napon = [napon1, napon2, napon3]
    jacina = [jacina1, jacina2, jacina3]
    
    plt.plot(jacina, napon, marker='o', linestyle='--', color='g', label=f'Prosječni otpor: {prosjecni_otpor:.2f} Ω')
    
    plt.xlabel('Jačina struje (A)')
    plt.ylabel('Napon (V)')
    plt.title('Graf Ohmovog zakona')
    plt.legend(loc='lower right')

    # 将图表渲染到指定容器
    Element("chart-container").write(fig)


function_proxy = create_proxy(runPython)
document.getElementById("button").addEventListener("click", function_proxy)
</py-script>
</body>
</html>

关键改进说明

  • 导入Element类,正确获取DOM元素。
  • 添加类型转换和异常捕获,处理无效输入。
  • 使用plt.clf()清空画布,避免图表叠加。
  • 修正div标签闭合问题,添加step属性优化输入体验。
  • 更新图表文本为欧姆定律相关内容,显示平均电阻值。
  • 将图表渲染到指定容器,布局更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:46:02