介紹
你好,這裡是 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 設定環境。
- 安裝 Flet:您可以使用 pip 安裝 Flet。您只需打開終端機或命令提示符,輸入此命令並運行它即可。
pip install flet
- 建立一個新的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)
運行程式碼以查看是否一切正常。如果您看到“你好,世界!”顯示後,您就可以開始建立我們的計算器了。
輸出
建立佈局
在本節中,我們將重點介紹計算器的結構;在這裡,我們將使用列小部件來堆疊我們的顯示和按鈕。顯示器將顯示目前輸入,按鈕將允許使用者互動。奇怪的是我從來沒有註意到 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)
運行上面的程式碼後,您將看到計算器佈局的輸出,它可能看起來不太好,但沒關係!我們將透過在容器上添加一些間距、半徑和主題來增強它,使我們的計算器看起來更加精緻。
輸出
程式碼解釋
好的,我們已經建立了佈局,對嗎?好吧,我仍然知道你們中的一些人不明白我們剛剛在這裡做了什麼。坐下來,沒有問題,讓我解釋一下程式碼的作用。
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,
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
- 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
- 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.
- 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.
- 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.
- 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
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中文網其他相關文章!

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...

如何使用正則表達式匹配到第一個閉合標籤就停止?在處理HTML或其他標記語言時,常常需要使用正則表達式來�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!