Create a GUI Calculator with Python

PythonBeginner
Practice Now

Introduction

In this project, we will guide you on how to create a basic GUI calculator using Python and the tkinter library. This calculator will be able to perform simple arithmetic operations such as addition, subtraction, multiplication, and division.

👀 Preview

GUI calculator interface preview

🎯 Tasks

In this project, you will learn:

  • How to set up the main tkinter window for the calculator
  • How to add a calculation function to perform arithmetic operations
  • How to create an entry field for users to input numbers and view results
  • How to add buttons for digits, arithmetic operations, and clear function
  • How to run the tkinter event loop to start the calculator

🏆 Achievements

After completing this project, you will be able to:

  • Use the tkinter library to create a graphical user interface
  • Bind functions to buttons to enable interactivity
  • Perform basic arithmetic operations in Python
  • Display and update results using an entry field

Create the Project File

Firstly, create a new python file named labex_calculator.py. This file will hold the code for our calculator. To create the file, you can use the terminal or GUI interface of your operating system.

## Creating a new python file
cd ~/project
touch labex_calculator.py
✨ Check Solution and Practice

Set up the Main Tkinter Window

To start building our calculator, open the labex_calculator.py file in a text editor. The firstly step of creating our calculator GUI (graphic user interface) is creating a main window. We'll do this with the tkinter library.

## Importing tkinter library
import tkinter as tk

## Creating main tkinter window/toplevel
root = tk.Tk()
root.title('LabEx Calculator') ## Setting the title of our calculator
root.geometry('400x600') ## Setting the size of our calculator
root.configure(background='light blue') ## Setting the background color of our calculator
✨ Check Solution and Practice

Add a Calculation Function

To enable the calculator to perform arithmetic operations, define a function calculate.

def calculate(event):
    text = event.widget.cget('text') ## Getting the text from the button
    if text == '=':
        try:
            result = str(eval(entry.get())) ## Calculate the result
            entry.set(result) ## Set the entry to the result
        except Exception as e:
            entry.set('Error') ## In case of error, set the entry to 'Error'
        return

    if text == 'C':
        entry.set('') ## If 'C' is pressed, clear the entry
        return
    entry.set(entry.get() + text) ## Adding the pressed button's text to the entry
✨ Check Solution and Practice

Create an Entry Field

Create an entry field for users to enter the numbers and see results of calculations.

entry = tk.StringVar()
entry.set('') ## Setting the initial entry to an empty string
entry1 = tk.Entry(root, textvar=entry, font='lucida 30 bold', bd=5, insertwidth=4, bg='powder blue', justify='right') ## Creating the entry field
entry1.pack(fill=tk.X, ipadx=8, pady=10, padx=10) ## Positioning the entry field
✨ Check Solution and Practice

Add Buttons

Next, add buttons to the calculator for digits, arithmetic operations, and clear function.

button_frame = tk.Frame(root) ## Create a frame for the buttons
button_frame.pack() ## Add the frame to the tkinter window

## A list for the buttons' text
button_list = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '.', '0', '=', '+',
    '00', '000', 'C'
]

## Creating and positioning the buttons
i = 0
for btn_text in button_list:
    button = tk.Button(button_frame, text=btn_text, font='lucida 20 bold', bg='skyblue', padx=15, width=5)
    button.grid(row=int(i/4), column=i%4, padx=3, pady=3)
    i += 1
    button.bind('<Button-1>', calculate) ## Binding the 'calculate' function to the button
✨ Check Solution and Practice

Run the Project

Finally, let's run the tkinter event loop to start the calculator.

root.mainloop()

Switch to the Desktop and run the project.

python labex_calculator.py
Calculator application interface
✨ Check Solution and Practice

Summary

Congratulations! You've now created a basic GUI calculator using Python and the tkinter library. You can run your calculator by running the labex_calculator.py script. In this project, we've covered creating a tkinter window, adding a calculation function, creating an entry field for the calculator, adding buttons to perform arithmetic operations, and running the calculator.