Code

How to Make a Simple Calculator in Python: Step-by-Step Instructions

How to Make a Simple Calculator in Python: Step-by-Step Instructions

Course with employment: “Profession Python Developer"

Learn More

Step 0: Gather the Necessary Tools

We recommend starting with learning the basics of the Linux operating system. Choose a suitable distribution, install it, and set up Python. Our articles will provide you with the information you need to quickly master all the steps.

  • What is Linux: A Guide to the Most Free Operating System
  • The Best Linux Distributions: Which Operating System Version to Choose
  • How to Run Python Offline and Online: A Beginner's Guide

For Python development, we use two key tools from the GNOME ecosystem: Builder and Cambalache. Builder is a modern integrated development environment (IDE) that provides a convenient and efficient coding process. Cambalache, in turn, is a visual editor that simplifies the creation of a GTK calculator GUI. These tools allow developers to easily create Python applications using the power of GNOME.

Both tools are available for download from the Flathub app store, which guarantees safe installation in an isolated environment. To install, go to the Builder and Cambalache tool pages and click the "Install" button. The system will automatically begin downloading via the package manager, and you will only need to confirm the installation when prompted. Flathub is a trusted source of applications, providing users with a secure and convenient installation experience.

If automatic application installation does not work, copy the download command from the application's web page and paste it into the terminal. Also, make sure your distribution supports Flatpak. If support is not available, you will need to configure it manually.

The work plan includes creating a project in GNOME Builder, integrating the Python library StringCalculator to handle arithmetic expressions, developing a user interface using Cambalache, and testing the calculator functionality. Let's get started?

Step 1: Create a Project in GNOME Builder

Launch GNOME Builder from the applications menu. Click the "Create a new project" button. In the window that opens, fill in the required fields.

  • Project name: calculator.
  • Application ID: can be left blank.
  • Programming language: select Python.
  • Template: install as GNOME Desktop Application.
  • Project location: select the folder on your computer where the calculator files will be stored.

Once all the fields are filled in, click the «Create project» button.

Screenshot: GNOME Builder / Skillbox Media

The left side of the Builder window shows the file structure of your project. Here you can see all the folders and files that make up your project. This is a convenient navigation tool, allowing you to quickly find and edit the elements you need. The file structure helps organize your work, providing easy access to each component of the project. Make sure you structure your files properly to simplify the development process and improve project manageability.

  • The data folder contains our calculator's description file, launcher icon, icons, and other resources.
  • The po folder stores the application's translation files into various languages.
  • The src directory contains all the program's source code.

By default, GNOME Builder creates isolated application builds using Flatpak technology. These applications run in separate containers, ensuring their complete independence from the underlying operating system. Isolation is managed using the Flatpak manifest, a .json configuration file. This file defines all the required application components, including system libraries, Python modules, and other dependencies. You will need to fill out this manifest, which will be presented as the org.gnome.Example.json file.

Screenshot: GNOME Builder / Skillbox Media

Step 2. Adding the StringCalculator Library

When developing a string calculator, it's essential to ensure accurate parsing of arithmetic expressions entered by the user. The program must correctly determine the order of operations, taking into account parentheses. Achieving this goal requires an algorithm that will parse the string character by character and recognize numbers, operators, and parentheses. Without such an algorithm, it's impossible to perform the correct sequence of calculations and guarantee an accurate result. Effectively recognizing expression elements is key to creating a robust and functional calculator.

For the expression 2 + (3 × 4), the calculator will first calculate the product in parentheses (3 × 4 = 12) and then add 2 to the result, resulting in 14. Using the Python library StringCalculator greatly simplifies this process, as it automatically performs all the necessary calculations, making it an ideal tool for working with mathematical expressions.

To integrate StringCalculator into the calculator, open the manifest file (org.gnome.Example.json) and add the following code to the beginning of the modules section. Builder will then automatically install the library and configure all the necessary dependencies. This will allow you to use StringCalculator's functionality in your project, providing more flexible options for working with string data.

The manifest must include a description of the application module. When you launch a project using the button in the top bar, the standard greeting "Hello, World!" is displayed on the screen. The absence of errors during the launch process confirms the successful installation of the StringCalculator module.

Screenshot: GNOME Builder / Skillbox Media

Step 3. Building the user interface

In In the src directory, locate the window.ui file, which contains the XML markup for the calculator interface. Right-click this file and select 'Open with', then point to 'External Program' and select Cambalache.

When you first launch Cambalache, the interface will be blank because it uses files with the .cmb extension. To resolve this, you need to export the file. To do this, click the three-dot button in the upper-right corner, select 'Export all UI', and close Cambalache. Builder will then display a message stating that the file on disk has been modified. Click 'Discard changes and reload', and then reload the project. A new window.cmb file will appear in the src folder, which should be opened in Cambalache.

Screenshot: Cambalache / Skillbox Media

First, remove the label that says Hello, World! Find the GtkLabel element with the label content in the project tree and delete it. Then add a GtkBox container in its place. To do this, open the Layout menu located above the layout, select GtkBox, hover over the desired location in the layout, right-click, and select Add object here.

Screenshot: Cambalache / Skillbox Media

To delete the third section, press Ctrl + Del. Then change the container orientation from horizontal to vertical. To do this, find the «orientation» section in the right panel and select the «vertical» value from the drop-down list. This will make your content look more structured and easier to read.

Screenshot: Cambalache / Skillbox Media

Add an additional GtkBox container with horizontal orientation to the top section. This will simplify the process of adding calculator components, as now you only need to left-click on the desired area of ​​the layout. Using a horizontal GtkBox allows you to more effectively organize interface elements and improve user interaction with the application.

Screenshot: Cambalache / Skillbox Media

Let's continue customizing the top section of the calculator. Add a field for entering arithmetic expressions to the left side of the interface. To do this, open the Control menu and select GtkEntry. Add a button to calculate the result to the right side by opening the Control menu again and selecting GtkButton. These elements will allow users to enter mathematical expressions and receive calculation results, which will make the calculator more functional and easier to use.

Screenshot: Cambalache / Skillbox Media

At the bottom of the main container, add a field to display the result by selecting the widget GtkTextView in the Display menu. This will allow you to effectively visualize data and improve user interaction. GtkTextView provides the ability to display multi-line text and provides flexibility in content formatting.

Our calculator's interface is nearing completion. Now you need to go back to the button and in the right panel in the label section add the text «CALCULATE».

Screenshot: Cambalache / Skillbox Media

For effective interaction with interface elements In the program, it is important to assign unique identifiers to each widget. To do this, select the desired widget and specify a value in the Object Id field in the right panel. We recommend using the following notation: for GtkEntry, set the identifier to entry, for GtkButton - calculate_button, and for GtkTextView - text_view. This will simplify further work with interface elements and ensure their correct functioning in the application.

To save the created interface in the window.ui file, click the button with three dots in the upper right corner. In the menu that opens, select the option «Export all UI». After that, in Builder, click the «Discard changes» button and restart the application. This will successfully save all changes you've made to the interface.

Step 4. Launch the Calculator

In the src folder in Builder, open the window.py file, where we'll develop the main calculator code. We'll start by adding the SolveMathProblem class from the StringCalculator Python library to the imports section. This will allow us to use functions for solving math problems, which is a key part of our calculator's functionality.

Now we need to add the declarations of the calculator interface widgets. After the template line `label = Gtk.Template.Child()`, insert the following code:

In the __init__ function in Python, add a button click event handler that will perform the calculations. To do this, connect the button's clicked signal to the on_calculate_clicked handler function using the following code: self.calculate_button.connect(«clicked», self.on_calculate_clicked). This will allow the program to respond to button clicks and run the necessary calculations.

In the __init__ method, create a text variable, which is an empty string to store the calculation history. All entered expressions and their results will be added to this variable, which will later be displayed in the text_view field. This way, users will be able to see a complete history of their calculations, which improves the user experience.

The calculator's initialization function should be implemented as follows:

A handler function should be added to the calculator to enhance its functionality. This function will be responsible for processing user-entered data and performing calculations, making the calculator more convenient and efficient to use. It is important to consider all possible use cases and ensure that operations are performed correctly. Adding this function will not only improve the user experience but will also make the calculator a more reliable tool for performing mathematical calculations.

The Python calculator is now available for use. Run the project via the button in the GNOME Builder top bar and test its functionality. For example, enter the expression 2 + 2 × 2 and make sure that the calculator correctly takes into account the order of operations, returning the result 6. Also, check how the program responds to division by zero or to pressing the button with an empty input field. This will allow you to evaluate the reliability and stability of the calculator.

Screenshot: GNOME Builder / Skillbox Media
Screenshot: GNOME Builder / Skillbox Media

What's next

The calculator is functional, but it can be improved. Let's consider a few suggestions for improvement.

  • Add side padding to the main GtkBox container to make the interface neater.
  • Add a clear button to the calculator expression input field.
  • Bind the on_calculate_clicked function to the Enter key for quick results without the mouse.
  • Try using the re.sub() function from the re module to remove extra spaces in the expression before processing. You can read more about this in the article on regular expressions in Python.

Here are some resources that will help you improve your calculator. These materials contain useful tips and tricks that will help improve the functionality and user interface. Use them to streamline your development process and improve the quality of your final product.

  • GTK 4 Documentation — a guide to creating interfaces.
  • Python GTK Tutorial — step-by-step instructions with code examples.
  • GNOME Discourse — a forum for discussion and sharing experiences.
  • Cambalache and GNOME Builder Documentation — guides to our tools for designing and developing GTK applications.