October 13, 2024

How to Use Brython in the Browser

Brython (Browser Python) allows you to run Python code directly in the web browser, enabling Python developers to create interactive web applications without needing to write JavaScript. This guide will show you how to set up and use Brython in your browser to run Python code alongside HTML and JavaScript.

Step 1: Set Up a Basic HTML Page

To get started with Brython, you’ll need a basic HTML file where you can include the Brython library and write your Python code. Here’s a simple example:

Example: Basic HTML Setup

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brython Example</title>
    <!-- Include the Brython library from a CDN -->
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js"></script>
</head>
<body onload="brython()">

    <h1>Hello, Brython!</h1>

    <!-- Your Python code will go here -->
    <script type="text/python">
    from browser import document

    # Change the text of the h1 element
    document["title"].text = "Hello from Python!"
    </script>

</body>
</html>
    

In this example:

  • The <script> tag in the <head> section includes the Brython library from a CDN (Content Delivery Network).
  • The <body onload="brython()"> attribute ensures that Brython is initialized when the page loads.
  • The Python code is written inside a <script type="text/python"> tag. Brython will process this code and execute it in the browser.

Step 2: Write Python Code in the Browser

With Brython set up, you can now write Python code inside the <script type="text/python"> tags. This code will be executed by Brython in the browser environment, allowing you to manipulate the DOM, handle events, and create interactive web pages.

Example: Simple DOM Manipulation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brython DOM Manipulation</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js"></script>
</head>
<body onload="brython()">

    <h1 id="title">Original Title</h1>
    <button id="change-title">Change Title</button>

    <script type="text/python">
    from browser import document

    # Define a function to change the title text
    def change_title(event):
        document["title"].text = "Title Changed by Brython!"

    # Bind the function to the button click event
    document["change-title"].bind("click", change_title)
    </script>

</body>
</html>
    

In this example:

  • The <h1> element has an ID of “title,” and the button has an ID of “change-title.”
  • The Python code uses the document object from the Brython browser module to access these elements by their IDs.
  • A function change_title is defined to change the text of the <h1> element when the button is clicked.
  • The bind method attaches the change_title function to the button’s click event.

Step 3: Using Python Libraries in Brython

Brython supports many Python standard libraries, and you can use them just as you would in a regular Python script. However, keep in mind that some libraries that depend on system-level features (like file I/O) are not available in the browser environment.

Example: Using the math Library in Brython

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brython Math Example</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js"></script>
</head>
<body onload="brython()">

    <p>The square root of 16 is: <span id="result"></span></p>

    <script type="text/python">
    import math
    from browser import document

    # Calculate the square root of 16
    result = math.sqrt(16)

    # Display the result in the span element
    document["result"].text = str(result)
    </script>

</body>
</html>
    

In this example:

  • The math library is imported and used to calculate the square root of 16.
  • The result is displayed in a <span> element with the ID “result.”

Step 4: Integrating Brython with JavaScript

Brython allows seamless integration between Python and JavaScript. You can call JavaScript functions from Python and vice versa, enabling you to leverage existing JavaScript libraries and frameworks in your Brython code.

Example: Calling a JavaScript Function from Brython

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Brython and JavaScript Integration</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js"></script>

    <!-- JavaScript function -->
    <script type="text/javascript">
    function showAlert(message) {
        alert(message);
    }
    </script>
</head>
<body onload="brython()">

    <button id="alert-button">Show Alert</button>

    <script type="text/python">
    from browser import document, window

    # Define a Python function to call the JavaScript function
    def call_js(event):
        window.showAlert("Hello from Brython!")

    # Bind the Python function to the button click event
    document["alert-button"].bind("click", call_js)
    </script>

</body>
</html>
    

In this example:

  • A JavaScript function showAlert is defined to display an alert box with a message.
  • The Python code calls this JavaScript function using the window object provided by Brython.
  • The alert is triggered when the user clicks the button.

Conclusion

Brython provides a powerful way to write Python code that runs directly in the browser, allowing you to create interactive web applications without needing to write JavaScript. By following the steps outlined above, you can set up