Python can also write the front end of the web page!

As a glue language, Python is really omnipotent. No, recently another Python3-based front-end development tool aimed at replacing JavaScript— Brython

easy to use? Let's try to write a calculator with it today:

However, we must first know that it is a client-side Web programming tool for Python, and what is the difference between it and JS?

1. Features

1. It is easy to embed a Python terminal in the page for testing

2. Running speed is close to CPyhon

3. Convenient writing, strong community, and agile development

If you have written both Python and JS, you will most likely feel that writing the same function in Python is more convenient than JS.

4. Like JS, you can start writing without installing anything

Let's do some simple experiments with Brython.

2. Experiment

0. Install

Like normal Python libraries, it can be installed via pip install brython.

Then execute in an empty directory:

python -m brython --install

1. Display Hello! on the page  :

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/[email protected]/brython.min.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document
document <= "Hello !"
</script>
</body>
</html>


Save this code as index.html, double-click to open it in the browser, and you can see the words Hello!:

principle:

In the head of the code, a brython.min.js module attached to the Brython engine is introduced to control the page using Python.

And between <script type="text/python"> and </script> is the corresponding Python code.

As you can see, if you want to display text in the document, you only need to enter directly:

document <= "你所需要显示的文本"

You'll see examples of using Brython to interact with pages using standardized DOM syntax later on.

2. Use HTML tags for text formatting:

If you want to bold text:

from browser import document, html
document <= html.B("Hello !")

Part bold, part not bold:

from browser import document, html
document <= html.B("Hello, ") + "world !"

i-tags:

document <= html.UL(html.LI(i) for i in range(5))

Hyperlink:

document <= html.A("Python实用宝典", href="https://pythondict.com")

The above example is as follows:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/[email protected]/brython.min.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document, html
document <= html.B("Hello !")
document <= html.UL(html.LI(i) for i in range(5))
document <= html.A("Python实用宝典", href="https://pythondict.com")
</script>
</body>
</html>

Effect:

3. Write a simple calculator

Write a simple graphic structure first, just use th and tr tags:

from browser import document, html
calc = html.TABLE()
calc <= html.TR(html.TH(html.DIV("0", id="result"), colspan=3) +
                html.TH("C", id="clear"))
lines = ["789/",
        "456*",
        "123-",
        "0.=+"]
calc <= (html.TR(html.TD(x) for x in line) for line in lines)
document <= calc

Then add some CSS styles to make this simple graphic architecture pretty:

<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>

Finally, you only need to do the event trigger of the operator, from the following line of code:

calc <= (html.TR(html.TD(x) for x in line) for line in lines)

It can be seen that all buttons are created as td tags, so we only need to get whether all these buttons are clicked:

for button in document.select("td"):
    button.bind("click", action)

It means that the action operation will be executed after the button is clicked, and the action operation is defined as follows:

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"


If it is not an = sign or a C sign,  string concatenation is performed .

If it is C number, clear result.

If it is an = sign, the result needs to be calculated, and the purpose can be accomplished by directly using  the eval() function  on the string .

Here is all the core code, which is really convenient to write.

You can visit the following address to experience this calculator written in Python:

https://pythondict.com/calculator.html

Complete source code:
https://pan.baidu.com/s/1d4ndpN1Lpzb6fpgqKJ7acQ 

Extraction code: v36f

Author: Ckend 

Source: Python Practical Collection



每个程序员都是从菜鸟开始成长起来的,没有人一开始就是程序员高手。菜鸟爱编程,专注于分享趣味的编程技巧,不限于Java, Python ,Go, Javascript等语言,让菜鸟爱上编程,进阶成为高手。
菜鸟编程大本营
长按2秒,输入:【福利】点这里,进菜鸟学PythonB站大本营

Guess you like

Origin blog.csdn.net/cainiao_python/article/details/107625077