How to Create a Calculator GUI with Python Tkinter as shown in Image ?
How to Create a Calculator GUI with Python Tkinter as shown in Image ?

How to Create a Calculator GUI with Python Tkinter as shown in Image ?

Best answer
Answer: Create an Entry widget as the display and a grid of Buttons (CE, C, backspace, digits 0 to 9, '.', +, -, *, /, =). Digit and operator buttons add their symbol to the display, = evaluates the expression, C clears everything, CE clears the current number and < deletes the last character.
Layout (rows of the grid):
| Display (Entry, black background, white text) | |||
| CE | C | < | |
| 7 | 8 | 9 | / |
| 4 | 5 | 6 | * |
| 1 | 2 | 3 | - |
| . | 0 | = | + |
Code
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.title("Calculator")
frame = tk.Frame(window, padx=10, pady=10)
frame.pack()
entry = tk.Entry(frame, relief=tk.SUNKEN, borderwidth=3, width=40,
bg="black", fg="white")
entry.grid(row=0, column=0, columnspan=4, ipady=4, pady=4)
def press(symbol):
"""Add a digit, '.' or operator to the end of the display."""
entry.insert(tk.END, symbol)
def equal():
try:
result = eval(entry.get()) # simple calculator only: input comes from the buttons
entry.delete(0, tk.END)
entry.insert(0, str(result))
except ZeroDivisionError:
messagebox.showerror("Error", "Cannot divide by zero")
except Exception:
messagebox.showerror("Error", "Invalid expression")
def clear_all():
"""C: clear the whole expression."""
entry.delete(0, tk.END)
def clear_entry():
"""CE: clear only the number being typed (after the last operator)."""
text = entry.get()
i = len(text)
while i > 0 and (text[i - 1].isdigit() or text[i - 1] == "."):
i -= 1
entry.delete(i, tk.END)
def backspace():
"""<: delete the last character."""
text = entry.get()
if text:
entry.delete(len(text) - 1, tk.END)
def make_button(text, row, col, command):
btn = tk.Button(frame, text=text, width=5, height=2, command=command)
btn.grid(row=row, column=col, padx=2, pady=2)
return btn
# Row 1: CE, C and backspace
make_button("CE", 1, 1, clear_entry)
make_button("C", 1, 2, clear_all)
make_button("<", 1, 3, backspace)
# Rows 2 to 5: digits and operators
layout = [
["7", "8", "9", "/"],
["4", "5", "6", "*"],
["1", "2", "3", "-"],
[".", "0", "=", "+"],
]
buttons = {}
for r, row in enumerate(layout, start=2):
for c, sym in enumerate(row):
if sym == "=":
buttons[sym] = make_button(sym, r, c, equal)
else:
buttons[sym] = make_button(sym, r, c, lambda s=sym: press(s))
window.mainloop()How it works
Test: the buttons were clicked from a test script (Python 3, tkinter 8.6); the display showed:
typed : 12+3.5
after < : 12+3.
after CE : 12+
typed : 12+8*2
after = : 28
after C : ''
[messagebox] Error - Cannot divide by zero
display : 7/0(The last test typed 7/0 and pressed =; the error box appeared and the display kept 7/0.)

Log in or create a free account to answer this question.