Welcome folks today in this blog post we will be running python arithmetic calculator
script inside browser using html5
using brython
library. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<html> <head> <meta charset="utf-8"> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.9.0/brython.min.js"> </script> </head> <body onload="brython()"> <script type="text/python"> </body> </html> |
Here we are including the brython
library cdn and loading it whenever page loads using the onload
attribute on body tag.
And after this just style the html
calculator using some css
code which is given below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<style> *{ font-family: sans-serif; font-weight: normal; font-size: 1.1em; } td{ background-color: #ccc; padding: 10px 30px 10px 30px; border-radius: 0.2em; text-align: center; cursor: default; } #result{ border-color: #000; border-width: 1px; border-style: solid; padding: 10px 30px 10px 30px; text-align: right; } </style> |
And now add the appropriate python
code inside the script
tags as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
from browser import document, html # Construction de la calculatrice calc = html.TABLE() calc <= html.TR(html.TH(html.DIV("0", id="result"), colspan=3) + html.TD("C")) lines = ["789/", "456*", "123-", "0.=+"] calc <= (html.TR(html.TD(x) for x in line) for line in lines) document <= calc result = document["result"] # direct acces to an element by its id def action(event): """Handles the "click" event on a button of the calculator.""" # The element the user clicked on is the attribute "target" of the # event object element = event.target # The text printed on the button is the element's "text" attribute value = element.text if value not in "=C": # update the result zone if result.text in ["0", "error"]: result.text = value else: result.text = result.text + value elif value == "C": # reset result.text = "0" elif value == "=": # execute the formula in result zone try: result.text = eval(result.text) except: result.text = "error" # Associate function action() to the event "click" on all buttons for button in document.select("td"): button.bind("click", action) |