大家都知道,HTML可以直接引入JavaScript脚本文件。有一天,博主就想到:HTML能不能直接引入Python脚本文件呢?
带着这个疑惑,博主查阅了一些资料,最终找到了一款开源工具:brython。该工具会自动将Python代码转换为JavaScript代码。
下面是博主的案例代码,分享给大家,注意相对路径。
./index.html
:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>网页计算器</title>
<link rel="stylesheet" href="./css/calculator.css">
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js"></script>
</head>
<body onload="brython()">
<script type="text/python" src="./script/calculator.python"></script>
</body>
</html>
./script/calculator.python
:
from browser import document, html
document <= html.H1("Brython.js网页计算器")
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 access 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)
./css/calculator.css
:
*{
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;
}
body {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size:2vw;
}