Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

2 Answers

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:

  • Pyscript: JavaScript Event Callbacks
  • PyScript: JavaScript and Python Interoperability
like image 70
John Hanley Avatar answered Sep 20 '25 11:09

John Hanley


<html>
    <head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <link rel = 'stylesheet' href = "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    </head>

  <body>
    <button id = "show_output" class = "btn btn-primary" type = "submit" pys-onClick="show_output">Show Output</button>
    <div id="output_div" style="margin-top: 10px;margin-bottom: 10px;"></div>
   
    <py-script> 
             
             def show_output(*args, **kwargs):
                output = Element("output_div")
                output.write("You Clicked Me!")
    </py-script>
  </body>
</html>
like image 32
Nimit Gupta Avatar answered Sep 20 '25 11:09

Nimit Gupta