Hook
Build multi-platform apps in Python
More breakout videos from this creator.
Here is how to build this modern looking calculator app in Python using the Flet library for the UI. We start by importing flet, then define a main function that takes a page object and will be our main app window. We set the title to "Flet Calculator", the window width to 320 and the height to 450, giving us a nice compact phone sized layout. Next we set a text control called result where we store the calculated amount, on launch it starts at zero as white text and the size 32. Now to the button click function. Every button we make is going to call the same function when clicked. Inside here, we use e.control.data to identify the pressed button. So we know which one was pressed. If data is C, result.value is set to 0. If data is equals, we run Python's eval on the current string in result.value. So if the display says 12 + 5, eval turns that into 17. We wrap it in a try except block so if someone makes an invalid expression and catches the error. For every other button, numbers and operators, we just append it to the current display text. And if the display is still showing the default zero, we replace it instead of appending. So we don't end up with something like 035. Next, the button helper function. This one function builds them all. We pass in the label, set data to that label, so button click knows what was pressed, and set expand to true. So buttons fill the row evenly. Finally, we lay everything out. We wrap the result text in a container, align it to the center right, padding 20, black background for that modern look. Then we add four rows of buttons below it for the numbers, operators, equals and clear key. Last step is to call ft.app with target equals main, run it and you've got a fully working calculator. Type in an expression, hit equals and Python's eval does the math for you. Let me know if you'd like to see how I use Flet build to ship an app.