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

Pyscript按钮未点击即置灰,py-click/pys-onClick失效求助

问题解决:Pyscript密码生成器按钮默认置灰

按钮默认置灰的核心原因是Pyscript无法找到py-click绑定的password_generation函数,新版本Pyscript会自动禁用绑定失败的交互元素。以下是两种可靠的解决方法:

方法一:改用@when装饰器绑定事件(推荐)

在新版本Pyscript中,使用装饰器绑定事件比py-click属性更稳定,能避免加载顺序导致的函数找不到问题。

修改步骤:

  1. 更新HTML按钮:移除py-click属性,同时避免使用Python内置名称(如len)作为元素ID,防止潜在冲突:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Password Generator</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="stylesheet" href="https://pyscript.net/releases/2024.7.1/core.css">
    <script type="module" src="https://pyscript.net/releases/2024.7.1/core.js"></script>
</head>
<body>
    <h1>Password Generator</h1>
    <p>Generate password with your key</p>
    <input type="text" id="seed" placeholder="Type keyword here..." />
    <input type="text" id="password-length" placeholder="Type length here..." />
    <button id="run" type="button">Generate</button>
    <div id="output"></div>
    <script type="py" src="./main.py" config="./pyscript.toml"></script>
</body>
</html>
  1. 修改main.py:用@when装饰器绑定点击事件,并确保函数逻辑正确:
from pyscript import when, Element
import random
import string

@when("click", selector="#run")
def password_generation():
    seed = Element("seed").value.strip()
    length_input = Element("password-length").value.strip()
    
    # 输入验证
    if not seed or not length_input.isdigit():
        Element("output").write("请输入有效的关键词和数字长度!")
        return
    
    length = int(length_input)
    # 密码生成逻辑(可自定义)
    chars = string.ascii_letters + string.digits + string.punctuation
    random.seed(seed)
    password = ''.join(random.choice(chars) for _ in range(length))
    
    Element("output").write(f"生成的密码:<strong>{password}</strong>")

方法二:确保函数全局可访问

如果坚持使用py-click属性,需要在main.py中将函数暴露到全局作用域:

from pyscript import Element
import random
import string

def password_generation():
    # 同方法一中的函数逻辑
    pass

# 将函数暴露到全局
window.password_generation = password_generation

关键说明:

  • Pyscript 2024+版本对事件绑定的可靠性要求更高,@when装饰器会在脚本加载完成后自动绑定事件,避免加载顺序问题。
  • 避免使用Python内置关键字(如len、str)作为HTML元素ID,防止命名冲突导致的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:57:42