top of page

Creating a calculator with a graphical user interface (GUI)

Creating a calculator with a graphical user interface (GUI) is a bit more involved, but it can be a great learning experience. We'll use the tkinter library, which comes with Python by default, to create the GUI. Here's a step-by-step guide:



  1. Import tkinter: Start by importing the tkinter library and creating the main window.


import tkinter as tk

# Create the main window
root = tk.Tk()
root.title("Calculator")
  1. Create Display: Create a display field where the user inputs and results will be shown.


display = tk.Entry(root, width=20, borderwidth=5)
display.grid(row=0, column=0, columnspan=4)
  1. Define Button Click Function: Create a function that handles button clicks and updates the display.


def button_click(number):
    current = display.get()
    display.delete(0, tk.END)
    display.insert(0, current + str(number))
  1. Create Buttons: Create buttons for numbers (0-9) and basic operations (+, -, *, /).


buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+'
]

row_val = 1
col_val = 0for button in buttons:
    tk.Button(root, text=button, padx=20, pady=20,
              command=lambda b=button: button_click(b) if b != '=' else calculate()).grid(row=row_val, column=col_val)
    col_val += 1if col_val > 3:
        col_val = 0
        row_val += 1
        
  1. Implement Calculation: Create a function to perform calculations when the '=' button is clicked.


def calculate():
    expression = display.get()
    try:
        result = eval(expression)
        display.delete(0, tk.END)
        display.insert(0, result)
    except:
        display.delete(0, tk.END)
        display.insert(0, "Error")
  1. Run the GUI: Run the GUI loop to start the calculator application.


root.mainloop()

The complete code should look like this:


import tkinter as tk

def button_click(number):
    current = display.get()
    display.delete(0, tk.END)
    display.insert(0, current + str(number))

def calculate():
    expression = display.get()
    try:
        result = eval(expression)
        display.delete(0, tk.END)
        display.insert(0, result)
    except:
        display.delete(0, tk.END)
        display.insert(0, "Error")

root = tk.Tk()
root.title("Calculator")

display = tk.Entry(root, width=20, borderwidth=5)
display.grid(row=0, column=0, columnspan=4)

buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+'
]

row_val = 1
col_val = 0for button in buttons:
    tk.Button(root, text=button, padx=20, pady=20,
              command=lambda b=button: button_click(b) if b != '=' else calculate()).grid(row=row_val, column=col_val)
    col_val += 1if col_val > 3:
        col_val = 0
        row_val += 1

root.mainloop()

Save this code to a .py file and run it using your Python interpreter. It will open a simple calculator GUI with number buttons and basic arithmetic operations. You can expand upon this by adding more functionality, error handling, and a polished design.

Related Posts

See All

Mastering Lists in Python

Introduction Lists are one of the most fundamental and versatile data structures in Python. They allow you to store and manipulate collections of items, making them an essential tool for any Python pr

Python Anonymous Function

In Python, an anonymous function is a function that is defined without a name. It is also known as a lambda function because it is created using the `lambda` keyword. Anonymous functions are typically

Python Inheritance

Like any other OOP languages, Python also supports the concept of class inheritance. Inheritance allows us to create a new class from an existing class. The new class that is created is known as subcl

Hey there,

I'm Pankaj Chouhan. If coding is making you feel stuck or overwhelmed, no need to worry—I've got your back! Let's team up to improve your skills, boost your earnings, and create a brighter future together.

  • Instagram
  • Youtube

Copyright © 2023 codeswithpankaj.com - All Rights Reserved.

codeswithpankaj.com

Powered by p4n.in

bottom of page