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

PyScript按钮禁用功能失效求助:点击按钮无法禁用另一按钮

解决点击按钮禁用另一个按钮的问题

你当前代码的核心问题是错误地把disabled当成CSS样式属性来设置,实际上它是HTML按钮的原生布尔属性,因此用setAttribute("style", "disabled:True")根本无法实现禁用效果。

修正方案:

  1. 禁用按钮:直接操作按钮元素的disabled属性,或者使用setAttribute设置disabled属性(布尔属性只要存在就生效,无需赋值True)。
  2. 修改按钮颜色:建议直接操作style对象的对应属性,避免覆盖原有样式。

修正后的完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://pyscript.net/releases/2023.11.1/core.css" />
    <script type="module" src="https://pyscript.net/releases/2023.11.1/core.js"></script>

</head>
<body>
    <div>
        <button  id="run" py-click="colorChange">NO CLICK</button>
        <button  id="run2" py-click="disableRunButton">CLICK</button>

    </div>
    <style>
        #run{ background-color: rgb(61, 139, 130)}
        #run2{ background-color: rgb(179, 28, 65)}
    </style>
    <py-script>
        from js import document
        runButton = document.getElementById("run")
        
        def colorChange(event):
            # 直接修改style属性,不覆盖原有样式
            runButton.style.backgroundColor = "red"

        def disableRunButton(event):
            # 方式1:直接设置disabled属性
            runButton.disabled = True
            # 方式2:用setAttribute设置(二选一即可)
            # runButton.setAttribute("disabled", "")
    </py-script>
</body>
</html>

额外说明:

  • 把原函数名disabled改成了disableRunButton,避免和属性名混淆,代码更清晰。
  • 如果需要重新启用按钮,只需设置runButton.disabled = False或者runButton.removeAttribute("disabled")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:25:11