Search code examples
pythonhtmlpyscript

How to change value with PyScript wihtout reloading page


is it possible to print my example code like i would do it in an normal Console. it just prints the values at once without waiting and doesn't delete the previous one.

    <!DOCTYPE html>
<html lang ="en">
<head>
    <meta charset ="UTF-8">
    <meta http-equive ="X-UA-Compatible" content "IE=edge">
    <meta name ="viewpoert" content="width = device-width, initial-scale=1.0">
    <title> Document </title>
    
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
    <div id="myNum" style="background: red;"></div>
<py-script>
import asyncio

for x in range (1,10):
    element = document.getElementById('myNum')
    element.innerHTML = x
    await asyncio.sleep(1)
    
</py-script>
</body>
</html>

Solution

  • You need to update the DOM to overwrite the previous value:

    ...
    <body>
        <div id="myNum" style="background: red;"></div>
    <py-script>
    import asyncio
    
    for x in range (1,10):
        element = document.getElementById('myNum')
        element.innerHTML = x
        await asyncio.sleep(1)
        
    </py-script>
    </body>
    </html>