Home > OS >  Calling py-script function from button-click with "pys-onClick=..." doesn't work?
Calling py-script function from button-click with "pys-onClick=..." doesn't work?

Time:10-21

I'm relatively new to PyScript and would like to run a function when a button is clicked. However, no matter what code I try, it doesn't seem to work. The button is clickable but doesn't appear to do anything. When I call the function manually (inside the py-script tag) it works fine. Am I missing something?

Here's my code and thank you for helping:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Test</title>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
  </head>

  <body>
    
    <button id="test" type="button" pys-onClick="speak">run test</button>

<py-script>

def speak():
    print("hello")

</py-script>


  </body>
</html>

CodePudding user response:

As it develops, some things in PyScript are moving targets. A couple of things about your code. First pys-onClick has been deprecated in favor of py-onClick in the more recent releases (including 'latest', which you use here). Second, to call the function from the button element, the syntax should currently read py-onClick="function()" (pys-onClick="function" did work in earlier releases). Finally, and I'm open to correction here, the 'print' method in your python code prints to the console (if you open the developer tools, you'll see it printed to the console each time you call the function). If you want the text to appear on the page, you'll need to write to the DOM. If I understand your intent correctly, this code will give you the result you're looking for.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Test</title>
    <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
    <script defer src="https://pyscript.net/latest/pyscript.js"></script>
  </head>

  <body>
    
    <button id="test" type="button" py-onClick="speak()">run test</button>
    <div id="display"></div>

<py-script>

def speak():
    Element('display').write("Hello")

</py-script>


  </body>
</html>

Keep in mind, as PyScript evolves, this syntax may not work with future releases as the developers and maintainers refine the framework. Cheers!

  • Related