Create a GUI Calculator With Python

PythonPythonBeginner
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

Alt text

🎯 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

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) tkinter(("`Tkinter`")) -.-> tkinter/ThemedWidgetsGroup(["`Themed Widgets`"]) tkinter(("`Tkinter`")) -.-> tkinter/VariablesGroup(["`Variables`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") tkinter/ThemedWidgetsGroup -.-> tkinter/button("`Clickable Button`") tkinter/ThemedWidgetsGroup -.-> tkinter/entry("`Text Field`") tkinter/ThemedWidgetsGroup -.-> tkinter/frame("`Container Frame`") tkinter/VariablesGroup -.-> tkinter/stringvar("`Text String Variable`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("`Catching Exceptions`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} tkinter/button -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} tkinter/entry -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} tkinter/frame -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} tkinter/stringvar -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/variables_data_types -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/numeric_types -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/strings -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/type_conversion -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/conditional_statements -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/for_loops -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/lists -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/tuples -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/function_definition -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/importing_modules -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/standard_libraries -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/catching_exceptions -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/data_collections -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} python/build_in_functions -.-> lab-298861{{"`Create a GUI Calculator With Python`"}} end

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

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

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

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

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

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
Alt text

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.

Other Python Tutorials you may like