In this article, we’ll explore how to build a calculator in Python that continues calculations based on previous results, includes error handling for invalid inputs, and implements a Graphical User Interface (GUI) using Tkinter. This will make the calculator both functional and visually appealing, enhancing user experience.
Step 1: Basic Calculator Logic
First, we’ll start with the core functionality of a calculator—handling basic arithmetic operations such as addition, subtraction, multiplication, and division. Our calculator will also store the last result, allowing users to perform further operations without manually re-entering it.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero")
return x / y
# Main calculation function
def calculate(operation, num1, num2):
if operation == 'add':
return add(num1, num2)
elif operation == 'subtract':
return subtract(num1, num2)
elif operation == 'multiply':
return multiply(num1, num2)
elif operation == 'divide':
return divide(num1, num2)
else:
raise ValueError("Invalid operation")
Step 2: Continuing Calculations with Previous Results
We’ll now enhance the calculator by allowing the user to continue calculations based on the result of the last operation.
def calculator():
last_result = None
while True:
if last_result is None:
num1 = float(input("Enter first number: "))
else:
num1 = last_result
operation = input("Enter operation (add, subtract, multiply, divide) or 'exit' to quit: ").lower()
if operation == 'exit':
print("Exiting calculator. Goodbye!")
break
num2 = float(input("Enter second number: "))
try:
result = calculate(operation, num1, num2)
print(f"Result: {result}")
last_result = result # Store the result for future calculations
except ValueError as e:
print(e)
Explanation:
- We added a
last_resultvariable to store the result of the previous calculation. - If there is a
last_result, the user can continue calculations without inputting the first number again. - This makes the calculator more user-friendly by streamlining the process of continued calculations.
Step 3: Adding Error Handling for Invalid Inputs
To further improve user experience, we’ll integrate error handling to manage invalid inputs and operations. This ensures that users don’t encounter unexpected crashes due to mistyped values or unsupported operations.
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a valid number.")
def calculator_with_error_handling():
last_result = None
while True:
if last_result is None:
num1 = get_number("Enter first number: ")
else:
num1 = last_result
operation = input("Enter operation (add, subtract, multiply, divide) or 'exit' to quit: ").lower()
if operation == 'exit':
print("Exiting calculator. Goodbye!")
break
num2 = get_number("Enter second number: ")
try:
result = calculate(operation, num1, num2)
print(f"Result: {result}")
last_result = result # Store the result for future calculations
except ValueError as e:
print(e)
Explanation:
- We created a
get_numberfunction that ensures the input is a valid number. If the input is invalid, it keeps asking until the user enters a valid number. - We also enhanced the calculator by wrapping the input and calculation logic with error handling to manage unsupported operations and invalid inputs.
Step 4: Creating a Graphical User Interface (GUI) using Tkinter
Now that we have a functional and robust command-line calculator, let’s make it more accessible by adding a GUI using the Tkinter library. This GUI will have buttons for numbers and operations, and a display to show the current expression and result.
import tkinter as tk
from tkinter import messagebox
def on_button_click(value):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current + str(value))
def clear():
entry.delete(0, tk.END)
def calculate_expression():
try:
expression = entry.get()
result = eval(expression)
entry.delete(0, tk.END)
entry.insert(0, result)
except Exception as e:
messagebox.showerror("Error", "Invalid Input")
# GUI Setup
root = tk.Tk()
root.title("Calculator")
entry = tk.Entry(root, width=20, borderwidth=5, font=('Arial', 24))
entry.grid(row=0, column=0, columnspan=4)
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2),
('0', 4, 1), ('+', 1, 3), ('-', 2, 3),
('*', 3, 3), ('/', 4, 3), ('C', 4, 0),
('=', 4, 2),
]
for (text, row, col) in buttons:
if text == 'C':
button = tk.Button(root, text=text, padx=20, pady=20, command=clear)
elif text == '=':
button = tk.Button(root, text=text, padx=20, pady=20, command=calculate_expression)
else:
button = tk.Button(root, text=text, padx=20, pady=20, command=lambda t=text: on_button_click(t))
button.grid(row=row, column=col)
root.mainloop()
Output:

Explanation:
- We used Tkinter to create a simple GUI with buttons for numbers and arithmetic operators.
- The calculator has an input field (entry widget) where the user can type expressions.
- We used the
eval()function to calculate the mathematical expression entered by the user. - There are buttons for each number, operation, a clear button (C), and an equal button (=) to display the result.
Here’s the complete Python code that combines the functionalities of a user-friendly calculator with continued calculations, error handling, and a graphical user interface (GUI) using Tkinter.
import tkinter as tk
from tkinter import messagebox
# Basic arithmetic functions
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero")
return x / y
# Main calculation function
def calculate(operation, num1, num2):
if operation == 'add':
return add(num1, num2)
elif operation == 'subtract':
return subtract(num1, num2)
elif operation == 'multiply':
return multiply(num1, num2)
elif operation == 'divide':
return divide(num1, num2)
else:
raise ValueError("Invalid operation")
# Get valid number input function
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("Invalid input. Please enter a valid number.")
# Text-based calculator with error handling and continued calculations
def calculator_with_error_handling():
last_result = None
while True:
if last_result is None:
num1 = get_number("Enter first number: ")
else:
num1 = last_result
operation = input("Enter operation (add, subtract, multiply, divide) or 'exit' to quit: ").lower()
if operation == 'exit':
print("Exiting calculator. Goodbye!")
break
num2 = get_number("Enter second number: ")
try:
result = calculate(operation, num1, num2)
print(f"Result: {result}")
last_result = result # Store the result for future calculations
except ValueError as e:
print(e)
# Functions for Tkinter GUI
def on_button_click(value):
current = entry.get()
entry.delete(0, tk.END)
entry.insert(0, current + str(value))
def clear():
entry.delete(0, tk.END)
def calculate_expression():
try:
expression = entry.get()
result = eval(expression)
entry.delete(0, tk.END)
entry.insert(0, result)
except Exception as e:
messagebox.showerror("Error", "Invalid Input")
# GUI setup using Tkinter
def create_gui():
root = tk.Tk()
root.title("Calculator")
global entry
entry = tk.Entry(root, width=20, borderwidth=5, font=('Arial', 24))
entry.grid(row=0, column=0, columnspan=4)
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2),
('0', 4, 1), ('+', 1, 3), ('-', 2, 3),
('*', 3, 3), ('/', 4, 3), ('C', 4, 0),
('=', 4, 2),
]
for (text, row, col) in buttons:
if text == 'C':
button = tk.Button(root, text=text, padx=20, pady=20, command=clear)
elif text == '=':
button = tk.Button(root, text=text, padx=20, pady=20, command=calculate_expression)
else:
button = tk.Button(root, text=text, padx=20, pady=20, command=lambda t=text: on_button_click(t))
button.grid(row=row, column=col)
root.mainloop()
# Run the GUI calculator
create_gui()
# Optionally, uncomment this line to run the text-based calculator in the console
# calculator_with_error_handling()
Key Features of the Code:
- Text-Based Calculator with Error Handling: The
calculator_with_error_handlingfunction provides a user-friendly console calculator that allows users to continue calculations with previous results and handles invalid inputs. - Basic Arithmetic Functions: Functions like
add,subtract,multiply, anddividehandle basic operations. Division includes error handling for dividing by zero. - Tkinter GUI Calculator: The
create_guifunction implements a graphical interface using Tkinter, complete with number and operation buttons, and a display to show expressions and results. - Button Actions: The GUI handles button clicks using the
on_button_clickandcalculate_expressionfunctions. The clear button (C) and the equal button (=) perform clearing and evaluation of expressions, respectively. - Error Handling in GUI: If the user enters an invalid expression, an error message box will pop up, making the calculator more robust and user-friendly.
Conclusion
In this article, we’ve built a Python calculator that offers several user-friendly features:
- The ability to continue calculations with previous results, streamlining workflow.
- Error handling for invalid inputs and operations, ensuring the program doesn’t crash.
- A graphical interface using Tkinter, making the calculator visually appealing and easier to use.
These enhancements not only improve the calculator’s functionality but also make it more engaging for users. Whether you’re building a command-line tool or a GUI-based application, Python provides the flexibility and tools needed to create intuitive and feature-rich programs. You can further enhance this calculator by adding advanced operations (like square roots or exponents) or styling the GUI with custom themes.





Leave a Reply