搜索
首页后端开发Python教程使用 Flet 和 python 构建计算器

介绍

你好,这里是 Arsey,一位 Python 演讲者,这是我的第一篇博客,我将指导您使用 Flet 构建这个简单的计算器应用程序。我很高兴与您分享这一点,我们开始吧。

在当今的数字时代,创建跨平台应用程序是必要的。由于可用的框架过多,选择合适的框架可能具有挑战性。 Flet 就是这样一个框架,它是一个 Python 库,使开发人员能够使用 Flutter(但针对 Python)轻松构建 Web、桌面和移动应用程序。

在本博客中,我们将探索如何使用 Flet 创建一个基本的计算器应用程序,说明这个框架是多么简单和高效。

为什么选择弗莱特?

当我开始编程时,我的目标是构建移动应用程序。由于没有明确的指导,我选择了 Python 作为我的第一语言。学习很有趣,但随着我获得更多经验,我意识到 Python 传统上不适合应用程序开发,它更常用于数据分析和相关任务。

现在学习 Android 开发,使用 Kotlin 进行原生开发,使用 Dart 和 Flutter 进行跨平台开发,感谢这个库 flet,我的目标又近了一步。

这种认识令人沮丧,直到我发现了 Kivy、Tkinter、Flet 等框架,它们允许使用 Python 来构建应用程序。与 Kivy 或 Tkinter 不同,这些框架很好,但需要大量定制才能开发出适用于 Android 和 iOS 的美观移动应用程序。这就是 flet 的闪光点。

Flet 是一个受 Flutter(Google 流行的 UI 工具包)启发的 Python 框架。使用 flet 可以获得的结果令人印象深刻,我很高兴能分享更多。

什么是舰队?

Flet 是一个 Python 包,允许开发人员直接使用 Flutter 的 UI 工具包构建用户界面。

Flet 的主要优势在于它结合了 Python 的简单性和 Flutter 丰富的 UI 功能,无需丰富的前端经验即可快速开发跨平台应用。

Flet 是一个包含电池的库,因此不需要 SDK,并且可以使用 Flutter 的 SDK 轻松扩展。

注意:对一些前端概念有基本的了解是有好处的,例如盒子模型、Flexbox 和 Grid 等布局结构以及定位。虽然您仍然可以在不了解这些知识的情况下进行操作,但我强烈建议您熟悉这些概念。
现在,解决这个问题,让我们开始构建我们的计算器!

设置环境

在开始编码之前,请确保您的计算机上安装了 Python。然后,按照以下步骤为 Flet 设置环境。

  1. 安装 Flet:您可以使用 pip 安装 Flet。您只需打开终端或命令提示符,输入此命令并运行它即可。

pip install flet

  1. 创建一个新的 Python 文件:成功安装后,打开您最喜欢的代码编辑器(如 VS-Code、Pycharm 等)并创建一个新的 Python 文件,将其命名为 main.py 或您最喜欢的名称。 感到兴奋吗?我敢打赌你就是!让我们首先使用开发者社区中最受欢迎的短语“Hello World!”来测试我们的安装

在我们的 Python 文件中,输入以下代码

import flet as ft

def main(page: ft.Page):
    page.add(ft.Text(value="Hello, World!"))

ft.app(target=main)

运行代码以查看是否一切正常。如果您看到“你好,世界!”显示后,您就可以开始构建我们的计算器了。

输出

Building a calculator using Flet with python

创建布局

在本节中,我们将重点介绍计算器的结构;在这里,我们将使用列小部件来堆叠显示和按钮。显示屏将显示当前输入,按钮将允许用户交互。奇怪的是我从来没有注意到 UI 可以意味着用户交互的用户界面。

现在编写如下代码。

from flet import (
    app, Page, Container, Column, Row,
    TextField, colors, border_radius, ElevatedButton, TextAlign, TextStyle
)


def main(page: Page):
    page.title = "Calculator"
    result = TextField(
        hint_text='0', text_size=20,
        color='white', text_align=TextAlign.RIGHT,
        hint_style=TextStyle(
            color=colors.WHITE, size=20
        ),
        read_only=True
    )

    def button_click(e):
        pass

    button_row0 = Row(
        [
            ElevatedButton(text='C',  on_click=button_click),
            ElevatedButton(text='^',  on_click=button_click),
            ElevatedButton(text='%',  on_click=button_click),
            ElevatedButton(text='/',  on_click=button_click),
        ]
    )
    button_row1 = Row(
        [
            ElevatedButton(text='7',  on_click=button_click),
            ElevatedButton(text='8',  on_click=button_click),
            ElevatedButton(text='9',  on_click=button_click),
            ElevatedButton(text='*',  on_click=button_click),
        ]
    )
    button_row2 = Row(
        [
            ElevatedButton(text='4',  on_click=button_click),
            ElevatedButton(text='5',  on_click=button_click),
            ElevatedButton(text='6',  on_click=button_click),
            ElevatedButton(text='-',  on_click=button_click),
        ]
    )
    button_row3 = Row(
        [
            ElevatedButton(text='1',  on_click=button_click),
            ElevatedButton(text='2',  on_click=button_click),
            ElevatedButton(text='3',  on_click=button_click),
            ElevatedButton(text='+',  on_click=button_click),
        ]
    )
    button_row4 = Row(
        [
            ElevatedButton(text='0',  on_click=button_click),
            ElevatedButton(text='.',  on_click=button_click),
            ElevatedButton(text='=',  on_click=button_click),
        ]
    )
    container = Container(
        width=350, padding=20,
        bgcolor=colors. BLACK,
        content=Column(
            [
                result,
                button_row0, button_row1, button_row2,
                button_row3, button_row4
            ]
        )
    )
    page.add(container)


if __name__ == '__main__':
    app(target=main)

运行上面的代码后,您将看到计算器布局的输出,它可能看起来不太好,但没关系!我们将通过在容器上添加一些间距、半径和主题来增强它,使我们的计算器看起来更加精致。

输出

Building a calculator using Flet with python

代码解释

好的,我们已经构建了布局,对吗?好吧,我仍然知道你们中的一些人不明白我们刚刚在这里做了什么。坐下来,没有问题,让我解释一下代码的作用。

In the first line, we import our controls. Flet controls are widgets used to lay out our application into a meaningful User Interface. But here we have imported app, Page, Container, Column, Row,
TextField, colors, border_radius, ElevatedButton, TextAlign, TextStyle.

Even though some of them are not entire widgets, like app, colors, border_radius, TextAlign, and TextStyle. These are classes and methods that provide us with extra functionalities of our application, for example
The app, allows us to launch our app in a standalone mode targeting to the main instance of our application.* colors* allow us to style our controls that support the color and bgcolor attribute without us struggling to define their names and border_radius allows us to curve the corners of our containers.

In line 7 we define the main app instance to Page; a page is a container for View Controls. So here I won’t go deep into views since it’s beyond the scope of this tutorial, but you reference here.

We now give the title to our page, with the page.titleattribute, the title on the title bar of our app.

In lines 9-16 is the result control with its required attributes, though it has many, we are gonna use these ones for this project, as you can see we have add a place holder of 0, giving it a size of 20, color to white, align text to right, and the read-only to true so we don’t allow external of soft keyboards to work directly in it.

Line 18 we defined our event handler, button_click this is where we will apply the logic to function our application, eventually making it a working calculator, but for now I just used a pass statement as a placeholder.

From lines 21 – 59, we defined our rows using the Row Widget, the row widget is a control that displays its children in a horizontal array or layout from left to right, similar to the linear layout in Android development, or inline elements in CSS the row controls works in the same way as them, it lays out controls in a horizontal axis or linearly.

Then the ElevatedButton_will represent buttons on the calculator’s UI, but notice we have given it the text and _onclick attributes, the text defines the data that will be displayed on the results when clicked using the onclick attribute that will call for the function button_click to handle events accordingly.

We have the container, the container is a control that will allow us to decorate a control with background color, spacing, applying borders and border radius, and position it with padding, margin, and alignment.

A container follows the box-model concept like the one for CSS as in the figure below,

Building a calculator using Flet with python

The column control, like the Row control, this one displays its children in a vertical array or layout from top to bottom, this will allow us to vertically lay our buttons in the right order.

Now after defining our UI elements, we need to display them to our application and then call it. We do that by using the page.add() method which allows us to add and build our UI logically.

Then we have to call our app in the stand-alone mode, and that’s what lines 74-75 accomplished.

Adding functionality

Update your button click function to match this code below.

def button_click(e):
        if e.control.text == "=":
            try:
                result.value = str(eval(result.value))
            except Exception:
                result.value = "Error"
        elif e.control.text == "C":
            result.value = ""
        # elif e.control.text == "^":
        # logic for powers
        # pass
        else:
            result.value += e.control.text
        result.update()

CODE EXPLANATION

Okay, what does this code do under the hood; the button_click function is designed to handle various button click events within our calculator app.
Save to apply our current changes then run the calculator and see the results.
Here is a breakdown of how the code works

  1. Retrieving the button text: when a button is clicked, the function retrieves the button’s text (e.g., ‘1’, ‘2’, ‘+’, ‘-‘, ‘C’, ‘=’) through the e.control.text. this tells the functions which button the user has interacted with
  2. Clearing the display: when the user clicks the ‘C’ button, the calculator’s input is cleared. The result is set to an empty string (“”), and the display is reset to 0. This effectively clears the display making the calculator ready for a new input. Talk but a fresh number meal.
  3. Evaluating expressions: if the user clicks the “=” button, the calculator needs to evaluate the current mathematical expression, here we used the str() and eval() functions, and the str() function houses the eval() function so that the result is directly converted into a string and theeval() function will compute the result of the expression, then displayed as a string to our calculator’s display. Or else if the expression is invalid, an exception is caught, and the “Error” message will be displayed instead.
  4. For the rest of the buttons like numbers and operators: the function will append the button’s text to the display (which is initially “0” or when cleared), it replaces “0” with the button value, otherwise it adds button value to the end of the display.
  5. After processing the button click, the page is updated via page.update() method call to refresh the UI and show the updated input or result on the calculator's display. So every time you click the button and see the value on the display or a result, this is what the page.update() does.

NOTE: The eval() function is a quick way to evaluate expression but it can be risky with un-trusted input because it executes/evaluates any Python code. In a more secure app, you’d use a safer method for evaluating mathematical expressions.

Exercise: test your knowledge, of how would you handle the exponent ‘^’ expression so that if the user clicks the exponent button it returns the required output. For example, if the user inputs 2^2 the output will be 4, 5^5=25, and 3^4=81. You get the idea.

Let me know how you approached to this problem in the comments, okay, all done, let’s continue.

Improving our UI

Previously the user interface did not look that catchy and awesome, so let’s improve it, and update the buttons to match the following code.

button_row0 = Row(
    [
        ElevatedButton(text='C', expand=1, on_click=button_click,
                       bgcolor=colors.RED_ACCENT, color=colors.WHITE),
        ElevatedButton(text='^', expand=1, on_click=button_click,
                       bgcolor=colors.BLUE_ACCENT_100,
                       color=colors.RED_900
                       ),
        ElevatedButton(text='%', expand=1, on_click=button_click,
                       bgcolor=colors.BLUE_ACCENT_100,
                       color=colors.RED_900
                       ),
        ElevatedButton(text='/', expand=1, on_click=button_click,
                       bgcolor=colors.BLUE_ACCENT_100,
                       color=colors.RED_900
                       ),
    ]
)
button_row1 = Row(
    [
        ElevatedButton(text='7', expand=1, on_click=button_click),
        ElevatedButton(text='8', expand=1, on_click=button_click),
        ElevatedButton(text='9', expand=1, on_click=button_click),
        ElevatedButton(text='*', expand=1, on_click=button_click,
                       bgcolor=colors.BLUE_ACCENT_100,
                       color=colors.RED_900
                       ),
    ]
)
button_row2 = Row(
    [
        ElevatedButton(text='4', expand=1, on_click=button_click),
        ElevatedButton(text='5', expand=1, on_click=button_click),
        ElevatedButton(text='6', expand=1, on_click=button_click),
        ElevatedButton(text='-', expand=1, on_click=button_click, 
                       bgcolor=colors.BLUE_ACCENT_100
                       ),
    ]
)
button_row3 = Row(
    [
        ElevatedButton(text='1', expand=1, on_click=button_click),
        ElevatedButton(text='2', expand=1, on_click=button_click),
        ElevatedButton(text='3', expand=1, on_click=button_click),
        ElevatedButton(text='+', expand=1, on_click=button_click, 
                       bgcolor=colors.BLUE_ACCENT_100,
                       color=colors.RED_900),
    ]
)
button_row4 = Row(
    [
        ElevatedButton(text='0', expand=1, on_click=button_click),
        ElevatedButton(text='.', expand=1, on_click=button_click),
        ElevatedButton(
            text='=', expand=2, on_click=button_click,
            bgcolor=colors.GREEN_ACCENT, color=colors.AMBER
        ),
    ]
)

What have we changed exactly, hmm!

For the buttons, we could have used the width attribute but that won’t work as we want it would break the UI, feel free to test it.
But we have this expand attribute which allows only a Boolean and an int data type value.

For the normal buttons like the operators, numbers, and the clear button we expanded them to 1, and for the equals button, we expanded it by 2.

Now what does the expand attribute do, the expand attribute allows a control to fill the available space in a given container.

So the buttons with expand 1 will have an equal size of width and for the equals button it will expand 2, or in simple terms span two buttons or will equal two buttons in width.

Notice that we have added colors and background colors to some of our buttons to make them stand out from the numbers buttons.
Understand, great.

In the container add these attributes, just after the padding attribute to make it look more appealing and user friendly.
border_radius=border_radius.all(20),

Output

Building a calculator using Flet with python

Now, you have a fully functional calculator built with Flet! Feel free to customize it to your liking or add more features. You can even package it as a standalone APK, AAB to launch on Google Play Store or Apple App Store

Here is the full code,

from flet import (
    app, Page, Container, Column, Row,
    TextField, colors, border_radius, ElevatedButton, TextAlign, TextStyle
)
from flet_core import ThemeMode


def main(page: Page):
    page.title = "Calculator"
    page.theme_mode = ThemeMode.DARK
    page.horizontal_alignment = page.vertical_alignment = 'center'
    result = TextField(
        hint_text='0', text_size=20,
        color='white', text_align=TextAlign.RIGHT,
        hint_style=TextStyle(
            color=colors.WHITE, size=20
        ),
        read_only=True
    )

    def button_click(e):
        if e.control.text == "=":
            try:
                result.value = str(eval(result.value))
            except Exception:
                result.value = "Error"
        elif e.control.text == "C":
            result.value = ""
        # elif e.control.text == "^":
        # logic for powers
        # pass
        else:
            result.value += e.control.text
        result.update()

    button_row0 = Row(
        [
            ElevatedButton(text='C', expand=1, on_click=button_click,
                           bgcolor=colors.RED_ACCENT, color=colors.WHITE),
            ElevatedButton(text='^', expand=1, on_click=button_click,
                           bgcolor=colors.BLUE_ACCENT_100,
                           color=colors.RED_900
                           ),
            ElevatedButton(text='%', expand=1, on_click=button_click,
                           bgcolor=colors.BLUE_ACCENT_100,
                           color=colors.RED_900
                           ),
            ElevatedButton(text='/', expand=1, on_click=button_click,
                           bgcolor=colors.BLUE_ACCENT_100,
                           color=colors.RED_900
                           ),
        ]
    )
    button_row1 = Row(
        [
            ElevatedButton(text='7', expand=1, on_click=button_click),
            ElevatedButton(text='8', expand=1, on_click=button_click),
            ElevatedButton(text='9', expand=1, on_click=button_click),
            ElevatedButton(text='*', expand=1, on_click=button_click,
                           bgcolor=colors.BLUE_ACCENT_100,
                           color=colors.RED_900
                           ),
        ]
    )
    button_row2 = Row(
        [
            ElevatedButton(text='4', expand=1, on_click=button_click),
            ElevatedButton(text='5', expand=1, on_click=button_click),
            ElevatedButton(text='6', expand=1, on_click=button_click),
            ElevatedButton(text='-', expand=1, on_click=button_click, 
                           bgcolor=colors.BLUE_ACCENT_100
                           ),
        ]
    )
    button_row3 = Row(
        [
            ElevatedButton(text='1', expand=1, on_click=button_click),
            ElevatedButton(text='2', expand=1, on_click=button_click),
            ElevatedButton(text='3', expand=1, on_click=button_click),
            ElevatedButton(text='+', expand=1, on_click=button_click, 
                           bgcolor=colors.BLUE_ACCENT_100,
                           color=colors.RED_900),
        ]
    )
    button_row4 = Row(
        [
            ElevatedButton(text='0', expand=1, on_click=button_click),
            ElevatedButton(text='.', expand=1, on_click=button_click),
            ElevatedButton(
                text='=', expand=2, on_click=button_click,
                bgcolor=colors.GREEN_ACCENT, color=colors.AMBER
            ),
        ]
    )
    container = Container(
        width=350, padding=20,
        bgcolor=colors.BLACK, border_radius=border_radius.all(20),
        content=Column(
            [
                result,
                button_row0, button_row1, button_row2,
                button_row3, button_row4
            ]
        )
    )
    page.add(container)


if __name__ == '__main__':
    app(target=main)

Conclusion

Building this calculator has been a fun experience for me and a learning experience for you, and I hope you enjoyed it too.

Let me know what kind of project you’d like to build using this framework or any other like PyQt, Kivy, or Tkinter. I’d be glad to make a tutorial on it. Or even web design and development tutorials, also are allowed.

Feel free to ask questions, I’ll do my best to answer them.
If you've read this far, thank you—I appreciate it!

以上是使用 Flet 和 python 构建计算器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何使用Python查找文本文件的ZIPF分布如何使用Python查找文本文件的ZIPF分布Mar 05, 2025 am 09:58 AM

本教程演示如何使用Python处理Zipf定律这一统计概念,并展示Python在处理该定律时读取和排序大型文本文件的效率。 您可能想知道Zipf分布这个术语是什么意思。要理解这个术语,我们首先需要定义Zipf定律。别担心,我会尽量简化说明。 Zipf定律 Zipf定律简单来说就是:在一个大型自然语言语料库中,最频繁出现的词的出现频率大约是第二频繁词的两倍,是第三频繁词的三倍,是第四频繁词的四倍,以此类推。 让我们来看一个例子。如果您查看美国英语的Brown语料库,您会注意到最频繁出现的词是“th

我如何使用美丽的汤来解析HTML?我如何使用美丽的汤来解析HTML?Mar 10, 2025 pm 06:54 PM

本文解释了如何使用美丽的汤库来解析html。 它详细介绍了常见方法,例如find(),find_all(),select()和get_text(),以用于数据提取,处理不同的HTML结构和错误以及替代方案(SEL)

如何在Python中下载文件如何在Python中下载文件Mar 01, 2025 am 10:03 AM

Python 提供多种从互联网下载文件的方法,可以使用 urllib 包或 requests 库通过 HTTP 进行下载。本教程将介绍如何使用这些库通过 Python 从 URL 下载文件。 requests 库 requests 是 Python 中最流行的库之一。它允许发送 HTTP/1.1 请求,无需手动将查询字符串添加到 URL 或对 POST 数据进行表单编码。 requests 库可以执行许多功能,包括: 添加表单数据 添加多部分文件 访问 Python 的响应数据 发出请求 首

python中的图像过滤python中的图像过滤Mar 03, 2025 am 09:44 AM

处理嘈杂的图像是一个常见的问题,尤其是手机或低分辨率摄像头照片。 本教程使用OpenCV探索Python中的图像过滤技术来解决此问题。 图像过滤:功能强大的工具 图像过滤器

如何使用Python使用PDF文档如何使用Python使用PDF文档Mar 02, 2025 am 09:54 AM

PDF 文件因其跨平台兼容性而广受欢迎,内容和布局在不同操作系统、阅读设备和软件上保持一致。然而,与 Python 处理纯文本文件不同,PDF 文件是二进制文件,结构更复杂,包含字体、颜色和图像等元素。 幸运的是,借助 Python 的外部模块,处理 PDF 文件并非难事。本文将使用 PyPDF2 模块演示如何打开 PDF 文件、打印页面和提取文本。关于 PDF 文件的创建和编辑,请参考我的另一篇教程。 准备工作 核心在于使用外部模块 PyPDF2。首先,使用 pip 安装它: pip 是 P

如何在django应用程序中使用redis缓存如何在django应用程序中使用redis缓存Mar 02, 2025 am 10:10 AM

本教程演示了如何利用Redis缓存以提高Python应用程序的性能,特别是在Django框架内。 我们将介绍REDIS安装,Django配置和性能比较,以突出显示BENE

引入自然语言工具包(NLTK)引入自然语言工具包(NLTK)Mar 01, 2025 am 10:05 AM

自然语言处理(NLP)是人类语言的自动或半自动处理。 NLP与语言学密切相关,并与认知科学,心理学,生理学和数学的研究有联系。在计算机科学

如何使用TensorFlow或Pytorch进行深度学习?如何使用TensorFlow或Pytorch进行深度学习?Mar 10, 2025 pm 06:52 PM

本文比较了Tensorflow和Pytorch的深度学习。 它详细介绍了所涉及的步骤:数据准备,模型构建,培训,评估和部署。 框架之间的关键差异,特别是关于计算刻度的

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器