pythonhtmlinputoutputpyscript

How do you input and output text with Pyscript?


I’m learning py-script where you can use <py-script></py-script> in an HTML5 file to write Python Code. As a python coder, I would like to try web development while still using python, so it would be helpful if we could output and input information using py-script.

For example, could someone explain how to get this function to work:

<html>
     <head>
          <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
          <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
     </head>
     <body>
          <div>Type an sample input here</div>
          <input id = “test_input”></input>
          <-- How would you get this button to display the text you typed into the input into the div with the id, “test”--!>
          <button id = “submit-button” onClick = “py-script-function”>
          <div id = “test”></div>
          <div 
<py-script>

<py-script>
     </body>
</html

I would appreciate it and I hope this will also help the other py-script users.


Solution

  • I checked source code on GitHub and found folder examples.

    Using files todo.html and todo.py I created this index.html
    (which I tested using local server python -m http.server)

    Some elements I figured out because I have some experience with JavaScript and CSS - so it could be good to learn JavaScript and CSS to work with HTML elements.

    <!DOCTYPE html>
    
    <html>
    
    <head>
      <!--<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />-->
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    </head>
    
    <body>
      <div>Type an sample input here</div>
      <input type="text" id="test-input"/>
      <button id="submit-button" type="submit" pys-onClick="my_function">OK</button>
      <div id="test-output"></div>
    
    <py-script>
    from js import console
    
    def my_function(*args, **kwargs):
    
        #print('args:', args)
        #print('kwargs:', kwargs)
    
        console.log(f'args: {args}')
        console.log(f'kwargs: {kwargs}')
        
        text = Element('test-input').element.value
    
        #print('text:', text)
        console.log(f'text: {text}')
    
        Element('test-output').element.innerText = text
    </py-script>
    
      </body>
    </html>
    

    Here screenshot with JavaScript console in DevTool in Firefox.

    It needed longer time to load all modules
    (from Create pyodine runtime to Collecting nodes...)

    Next you can see outputs from console.log().
    You may also use print() but it shows text with extra error writing to undefined ....

    enter image description here