Hi everyone, I made a random number generator using PyScript. It generates a random number between 1 to 100. Nothing fancy, just wanted to test it out.
https://infinitepower18.github.io/randomnumber-pyscript/
I’m yet to figure out a way to make the generate new number button work without refreshing the page, but you’re more than welcome to submit a PR to the GitHub repo 
1 Like
I tried to create a PR but received a 403.
Here are the changes to make the button work without refreshing the page.
I wrote a number of articles on PyScript. This one covers event callbacks and handlers which I used to modify your code.
index.html
Notice the new <div>
which holds the output from the generator
<button>
was changed to add an “id” so that it can be referenced from Python.
<body>
<h1 style="font-size:30px;">Random Number Generator</h1>
<py-script src="./generator.py"></py-script>
<div id="output"></div>
<button id="generate" class="p-2 text-white bg-blue-600 border border-blue-600 rounded" type="button" >Generate new number</button>
<br><br>
Check out the source code on <a href="https://github.com/infinitepower18/randomnumber-pyscript"><u>GitHub</u></a>
</body>
generator.py
The function generate()
is now triggered by a button click. Since this is a callback function (event handler) you cannot call print()
. Output is stored in the <div>
import random
from js import document
from pyodide import create_proxy
def generate(event):
s = "Your random number is " + str(random.randint(1,100))
document.getElementById("output").innerHTML = s
document.getElementById("generate").addEventListener("click", create_proxy(generate))
1 Like
Thanks a lot! I think GitHub was having an outage when you tried to create the PR.
1 Like