Search code examples
pythonhtmlpyscript

How do I call a python script when clicking a button (using pyscript)


I would like to run an Python script on Browser when clicking a button (on a html file). Something close to this:

<!DOCTYPE html>
<html>

<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
</py-env>
</head>

<body>

<button type="button" onclick="runPython()">run Python</button>

<script>
function runPython() { 

<py-script>
print("you clicked me")
</py-script>

}
</script>

</body>
</html>

Solution

  • To call Python code from JavaScript requires creating a proxy. This proxy handles type (data) translation to and from JavaScript.

    To create a proxy:

    from js import document 
    from pyodide import create_proxy
    
    function_proxy = create_proxy(runPython)
    

    Change your HTML element declaration to declare an ID and remove the onClick:

    <button type="button" id="button">run Python</button>
    

    Assign the proxy to an event listener for the button:

    e = document.getElementById("button")
    e.addEventListener("click", function_proxy)
    

    This style is very similar to how JavaScript also assigns event listeners.

    Put this together:

    <body>
    
    <button type="button" id="button">run Python</button>
    
    <py-script>
    from js import document 
    from pyodide import create_proxy
    
    def runPython():
        print("you clicked me")
    
    function_proxy = create_proxy(runPython)
    
    document.getElementById("button").addEventListener("click", function_proxy)
    </py-script>
    
    </body>
    

    I wrote several articles on JavaScript and Python: