Setting up Python event handlers in Pyscript requires special handling. Pyodide provides a proxy so that DOM events can use Python functions as callbacks.

To create a proxy, call the pyodide.create_proxy() function [link].

The Python function myFunction is a normal Python function that will be called on an event.

To assign the proxy function to a listener:

Pyscript Examples

Here is a complete example that increments a counter for each button press. You can see this example on my website.

Button Proxy Example

Time-Based Callbacks

Python developers typically write procedural code. When designing for the browser, you want to be careful to not lock up the user interface. A web browser provides one thread for a web application. To use more threads, you must use Web Workers. There are times that you want to perform tasks on a schedule, for example, updating a stock quote, refreshing page content, etc. Browsers provide the API setInterval() [link] to callback to your application at a fixed interval.

This example sets up a callback every 1,000 ms and updates the browser page with a counter. Once the counter reaches 15, the interval callback is canceled.

Interval Proxy Example

Notice that the same call to create_proxy() is used.


Interfacing with HTML and JavaScript is fairly easy to do. Pyscript and Pyodide have created very nice libraries and interfaces for Python development in the browser.

More Information

Photography Credit

I write free articles about technology. Recently, I learned about which provides free images. The image in this article is courtesy of Tina Nord at Pexels.