Learn how to use the Brython Python graphics library outside of CodeHS on any website.
Brython is a Python graphics library designed to replace Javascript as the scripting language for the web. This tutorial walks you through how you can take a Brython program and embed it in a webpage.
Create an HTML file named index.html
. You can do this either in the CodeHS Sandbox by creating an HTML program or locally on your computer. You can add the following HTML skeleton code:
Between the head
tags, include the following script
tags, which link an external JavaScript file with the Brython library:
Next, we will add a large Python script to allow your program to recognize available Brython commands for adding shapes, images, colors, and more.
First, create a Python file called brython_graphics.py
. In this file, paste the following code:
The onload
event occurs when an object has been loaded. To load the Brython library, we need to call brython()
on page load.
In the body
tag, add the onload
attribute and set its value to "brython()"
.
In this step we will add your Brython script to the website. Create a file called main.py
.
In main.py
:
Import the brython_graphics
module you created in brython_graphics.py
.
Now that you have created your Brython program, we need to add it to the HTML page. Between the body
tags, add the following code snippet:
We need to add a canvas to the HTML page. In the body
tag, add the following code snippet:
To add some add a border around the canvas, let’s add some styling. Betewen the head
tags, add the following CSS style block:
Here’s an example showing a full HTML program for running Brython Graphics outside of CodeHS. We’ve hosted it in CodeHS, but this HTML will work on any site! You can view it here.