← Back to Projects
Python GUI Calculator (Smart Version)
import tkinter as tk
def press(num):
current = entry.get()
if current == "0":
if num in "0123456789":
entry.delete(0, tk.END)
entry.insert(0, str(num))
else:
entry.insert(tk.END, str(num))
else:
last_char = current[-1]
if last_char in "+-*/" and num == "0":
entry.insert(tk.END, str(num))
elif current[-2:] in ("+0", "-0", "*0", "/0") and num in "123456789":
entry.delete(len(current)-1, tk.END)
entry.insert(tk.END, str(num))
else:
entry.insert(tk.END, str(num))
def equal():
expression = entry.get()
if expression.strip() == "":
entry.delete(0, tk.END)
entry.insert(0, "Error")
return
try:
result = eval(expression)
if isinstance(result, float) and result.is_integer():
result = int(result)
entry.delete(0, tk.END)
entry.insert(0, str(result))
except Exception:
entry.delete(0, tk.END)
entry.insert(0, "Error")
def clear():
entry.delete(0, tk.END)
entry.insert(0, "0")
root = tk.Tk()
root.title("Smart Calculator")
root.geometry("360x450")
root.resizable(False, False)
entry = tk.Entry(root, font=("Arial", 24), bd=10, relief=tk.RIDGE, justify="right")
entry.grid(row=0, column=0, columnspan=4, sticky="nsew", padx=10, pady=10)
entry.insert(0, "0")
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
]
for (text, row, col) in buttons:
if text == '=':
btn = tk.Button(root, text=text, font=("Arial", 18), bg="#4CAF50", fg="white",
command=equal)
else:
btn = tk.Button(root, text=text, font=("Arial", 18),
command=lambda t=text: press(t))
btn.grid(row=row, column=col, sticky="nsew", padx=5, pady=5)
clear_btn = tk.Button(root, text='C', font=("Arial", 18), bg="#f44336", fg="white", command=clear)
clear_btn.grid(row=5, column=0, columnspan=4, sticky="nsew", padx=10, pady=10)
for i in range(6):
root.grid_rowconfigure(i, weight=1)
for i in range(4):
root.grid_columnconfigure(i, weight=1)
root.mainloop()