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

使用PyScript获取HTML输入框值失败,求原因及解决方法

PyScript获取输入框内容返回None的解决办法

问题场景

在HTML项目中使用PyScript开发,预期点击提交按钮后将上方文本替换为输入框的值,但代码仅返回None,无法获取输入框内容。

原HTML代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>PyScript Template</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
        - paths:
            - /demo.py
    </py-env>
</head>

<body style="font-family:Times New Roman;margin-left:40px">

    <br>
    <p id=main_description class=text>
        Hello, world.
    </p>

    <input class=player_input type=text id=input_box name=input autocomplete=off placeholder="What will you do?">
    <button type=button id=submit pys-onclick=submit_input>submit</button>

    <py-script src=/demo.py></py-script>
</body>

</html>

原PyScript代码:

# demo.py

def submit_input(e):
    input_box = Element("input_box")
    player_input = input_box.select(".value")
    main_description = Element("main_description")
    main_description.write(player_input)

问题原因

错误使用了select(".value")方法获取输入框值:PyScript的Element对象中,select()方法用于选择当前元素下的子元素,而非获取表单元素的输入值,因此返回None。对于输入框这类表单元素,需直接访问.value属性来获取内容。

修正后的代码

修改demo.py中的逻辑,直接通过.value属性获取输入框内容:

# demo.py
def submit_input(e):
    input_box = Element("input_box")
    # 直接访问.value属性获取输入框的文本内容
    player_input = input_box.value
    main_description = Element("main_description")
    main_description.write(player_input)

说明

  1. 通过Element("input_box")获取输入框对应的PyScript Element对象
  2. 访问该对象的.value属性,即可得到用户在输入框中输入的文本
  3. 最后调用main_description.write(player_input),将输入内容写入目标<p>标签,完成文本替换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 10:45:40