js可以两个标签一起bind吗_Python 竟然也可以写网页前端了!

2afe95ae8603085b011d2873b82a9bad.gif

作者:Ckend

来源:Python实用宝典

Python作为胶水语言,真的是无所不能。这不,最近又出现一个基于 Python3,目标是替代 JavaScript 的前端开发工具 — Brython

好用吗?咱今天来试试用它写一个计算器:

c0e8d31c73ee79cd7e1b23ee19aa9854.png

不过,我们首先要知道它作为 Python 的客户端 Web 编程工具,和 JS 有什么区别呢?

1. 特点

1. 可轻易地在页面中内嵌 Python 终端进行测试

8333aff7b1606726c0c4f2f36500b396.png

2. 运行速度接近于 CPyhon

3. 写法方便,社区强大,可进行敏捷开发

如果 Python 和 JS 你都写过,那大概率会觉得相同的功能,用 Python 写起来比 JS 更方便。

4.和 JS 一样,你不用安装任何东西就可以开始编写

下面就用Brython做一些简单的实验吧。

2. 实验

0. 安装

与通常的 Python 库一样,可以通过 pip install brython 进行安装。

然后在一个空目录下执行:

python -m brython --install
1. 在页面上显示  Hello !
src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js">from browser import documentdocument <= "Hello !"


将这份代码保存为index.html,双击在浏览器中打开,即可看到Hello !字样:

31ffb38b407858d17fc9c43a3064251b.png

原理:

代码的 head 中,引入了一个 Brython 引擎附带的 brython.min.js 模块,用于使用 Python 控制页面。

而在

可以看到,想在 document 中显示文本,只需要直接输入:

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

后续你将会看到用 Brython 使用标准化的 DOM 语法和页面交互的例子。

2. 用 HTML 标签来做文本格式化:

如果要加粗文本:

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

部分加粗、部分不加粗:

from browser import document, htmldocument <= html.B("Hello, ") + "world !"
i 标签:
document <= html.UL(html.LI(i) for i in range(5))
超链接:
document <= html.A("Python实用宝典", href="https://pythondict.com")
以上例子如下:
src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js">from browser import document, htmldocument <= html.B("Hello !")document <= html.UL(html.LI(i) for i in range(5))document <= html.A("Python实用宝典", href="https://pythondict.com")
效果:

9f31d9cb264573bbb2775beafe3d3552.png

3. 写一个简单的计算器

先写好简单的图形架构,用th和tr标签即可:

from browser import document, htmlcalc = 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

bee6b4453667bede153824639d58ea67.png

11caf154f97c39c11fc9f3994e3de7be.png

然后加上一些 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;}

479919027fed97e2e4e2ee52605e4a17.png

最后只需要做运算符的事件触发器即可,从下面这行代码:

calc <= (html.TR(html.TD(x) for x in line) for line in lines)
可以看出,所有的按钮都被创建为 td 标签,因此我们要获得所有这些按钮是否被点击,仅需要:
for button in document.select("td"):    button.bind("click", action)
意思是,按钮被点击后便执行 action 操作,action 操作定义如下:
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"

bccbb4bf998f48d3e2ea481ac93ba6b4.png

如果不是 = 号或 C 号,则进行 字符串拼接

如果是 C 号,则清空 result。

如果是 = 号,则需要计算出结果,直接对字符串用 eval() 函数 即可完成目的。

这边是全部核心代码了,写起来真的极其方便。

你可以访问如下地址体验这个 Python 写的计算器:

https://pythondict.com/calculator.html

完整源码:
https://pan.baidu.com/s/1d4ndpN1Lpzb6fpgqKJ7acQ 

提取码:v36f

---------End---------

顺便给大家推荐下我的微信视频号「价值前瞻」,主要分享读书、成长和投资思考,可以了解不一样的我,欢迎扫码关注。

b05487946e385616fe1f5bd0062087ec.png

是的,Python可以用来开发聊天软件。以下是几种常见的方法: 1. 使用Python中的socket模块和网络编程知识来实现客户端-服务器模型的聊天软件。 2. 使用Python中的GUI库,例如Tkinter,PyQt或wxPython,来创建可视化聊天窗口。 3. 使用Python中的自然语言处理库,例如NLTK或spaCy,来实现AI聊天机器人。 4. 使用Python中的第三方库,例如Flask或Django,来创建Web聊天应用程序。 以下是一个简单的示例,展示如何使用Python和Tkinter创建一个聊天小程序: ```python from tkinter import * from tkinter import messagebox root = Tk() root.title("Chat") root.geometry("400x500") # 创建聊天记录框 chatlog = Text(root, bd=0, bg="white", height="8", width="50", font="Arial",) chatlog.config(state=DISABLED) # 创建滚动条 scrollbar = Scrollbar(root, command=chatlog.yview, cursor="heart") chatlog['yscrollcommand'] = scrollbar.set # 创建发送消息框 user_input = StringVar() user_input.set("") entry_field = Entry(root, text=user_input, font="Arial") entry_field.bind("<Return>", send) # 创建发送按钮 send_button = Button(root, text="Send", font="Arial", command=send) # 把聊天记录框、滚动条、发送消息框和发送按钮放入窗口 scrollbar.place(x=376, y=6, height=386) chatlog.place(x=6, y=6, height=386, width=370) entry_field.place(x=128, y=401, height=90, width=265) send_button.place(x=6, y=401, height=90) # 发送消息 def send(event=None): msg = user_input.get() if msg != "": chatlog.config(state=NORMAL) chatlog.insert(END, "You: " + msg + "\n\n") chatlog.config(foreground="#442265", font=("Verdana", 12 )) res = "AI: I'm sorry, I don't understand." chatlog.insert(END, res + "\n\n") chatlog.config(state=DISABLED) chatlog.yview(END) user_input.set("") root.mainloop() ``` 这是一个非常基础的聊天小程序,只有发送消息和接收AI回复的功能,但你可以通过添加更多的代码和功能来扩展它。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值