如何使用PyScript从HTML到Python解析布尔值

e0bqpujr  于 2023-05-02  发布在  Python
关注(0)|答案(1)|浏览(112)

在PyScript应用程序中,我在index.html中提供了两个单选按钮,允许用户决定各向同性高斯blob的合成是否应该重叠(有效地通过切换make_blobs方法的Scikit-Learncluster_std值)。
应用参考:https://24ec0d6b-0b55-49be-aeb7-a0046c41abf4.pyscriptapps.com/ea775901-75b9-406d-beac-944d26301b09/latest/
我目前无法将选择解析为Python布尔值(TrueFalse),并且无论单击哪个单选按钮,都始终接收True值。
尝试将HTML中的值定义为双引号、单引号或未加引号,并在不同的大小写(标题、上部、下部)之间切换,但没有成功。也看了其他例子/问题在这里SO,E.例如How to pass a boolean from javascript to python?
HTML中相关部分的代码段:

<div id="input" style="margin: 20px;">
  Should the clusters overlap: <br/>
  <input py-click="generate_blobs()" type="radio" id="true" name="overlaps" value="true">
  <label for="true"> True</label>
  <input py-click="generate_blobs()" type="radio" id="false" name="overlaps" value="false">
  <label for="false"> False</label>
</div>

对于Python代码段也是如此:

def generate_blobs():
    """Generate isotropic Gaussian blobs for clustering"""

    over_laps = js.document.getElementsByName("overlaps")
    for element in over_laps:
        if element.checked:
            overlap = bool(element.value)

            print(overlap, type(overlap))
            
            break
    paragraph = Element("Overlap")
    paragraph.write(f"overlaps: {overlap}")

    n_samples = 4_000  # if overlap else 2_000
    cluster_std = 1.5 if overlap else .4

    X, y = datasets.make_blobs(
            n_samples = n_samples,
            n_features = 2,
            centers = 5,
            cluster_std = cluster_std,
            shuffle = True,
        )

    return X, y

设置“假”选项的结果:

任何建议都是最受欢迎的,因为我用完的想法尝试

4bbkushb

4bbkushb1#

您的问题是由使用py-click引起的。
py-click无法从Javascript传递click-event。
考虑对js.document.querySelectorAll的结果使用addEventListener,这样您将获得可用于获取值的事件
不要忘记将函数 Package 在create_proxy中,以确保在需要时将其删除。
小例子:

.as-console-wrapper { max-height: 45px !important; }
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title></title>
        <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
        <script defer src="https://pyscript.net/latest/pyscript.js"></script>
    </head>
    <body>
        <div id="input" style="margin: 20px;">
            Should the clusters overlap: <br/>
            <input type="radio" id="true" name="overlaps" value="true">
            <label for="true"> True</label>
            <input type="radio" id="false" name="overlaps" value="false">
            <label for="false"> False</label>
        </div>
        <py-script>
            from pyodide.ffi import create_proxy

            def onInputClick(e):
                elementId = e.target.id
                elementValue = e.target.value

                print(f"Clicked on <{elementId}>, new value: <{elementValue}>")

            for i in js.document.querySelectorAll('input'):
                i.addEventListener("click", create_proxy(onInputClick))
        </py-script>
    </body>
</html>

相关问题