Python can even write front-end web pages!

As a glue language, Python is really omnipotent. No, there is another front-end development tool based on Python3 recently with the goal of replacing JavaScript — Brython

is it useful? Let's try writing 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. You can easily embed the Python terminal in the page for testing

2. Running speed close to Cpyhon

3. It is easy to write, the community is strong, and agile development is possible

If you have written both Python and JS, you will most likely feel that the same functions are more convenient to write in Python than in JS.

4. Like JS, you don't have to install anything to start writing

Let's do some simple experiments with Brython.

2. Experiment

0. Install

As with 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 that comes with the Brython engine is introduced to control the page using Python.

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 <= "你所需要显示的文本"

Later you will see examples of using Brython to interact with pages using standardized DOM syntax.

2. Use HTML tags to format the text:

If you want to bold text:

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

Some bold, some not bold:

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

i tag:

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 graph structure first, using 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)

As you can see, all the buttons are created as td tags, so to get whether all these buttons are clicked, we only need:

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

It means that after the button is clicked, the action operation is executed. 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 = sign, you need to calculate the result, and you can use the  eval() function  directly on the string to complete the purpose.

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 http://10.200.1.11:23101/article/api/json?id=326841998&siteId=291194637