Advertisement
CodeCrusader

Calculator GUI

Jun 10th, 2023
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | Software | 0 0
  1. import tkinter as tk
  2.  
  3. # Initialize the window
  4. window = tk.Tk()
  5. window.title("Calculator")
  6.  
  7. # Entry widget to display and input numbers
  8. entry = tk.Entry(window, width=25, font=("Arial", 12))
  9. entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
  10.  
  11. # Function to handle button clicks
  12. def button_click(number):
  13.     current = entry.get()
  14.     entry.delete(0, tk.END)
  15.     entry.insert(tk.END, current + str(number))
  16.  
  17. def button_clear():
  18.     entry.delete(0, tk.END)
  19.  
  20. def button_equal():
  21.     try:
  22.         result = eval(entry.get())
  23.         entry.delete(0, tk.END)
  24.         entry.insert(tk.END, result)
  25.     except Exception:
  26.         entry.delete(0, tk.END)
  27.         entry.insert(tk.END, "Error")
  28.  
  29. # Create number buttons
  30. buttons = [
  31.     ("7", 1, 0),
  32.     ("8", 1, 1),
  33.     ("9", 1, 2),
  34.     ("4", 2, 0),
  35.     ("5", 2, 1),
  36.     ("6", 2, 2),
  37.     ("1", 3, 0),
  38.     ("2", 3, 1),
  39.     ("3", 3, 2),
  40.     ("0", 4, 0),
  41. ]
  42.  
  43. for button in buttons:
  44.     text, row, column = button
  45.     tk.Button(window, text=text, width=5, height=2, command=lambda t=text: button_click(t)).grid(row=row, column=column)
  46.  
  47. # Create operator buttons
  48. operators = [
  49.     ("+", 1, 3),
  50.     ("-", 2, 3),
  51.     ("*", 3, 3),
  52.     ("/", 4, 3),
  53.     ("=", 4, 2),
  54.     ("C", 4, 1),
  55. ]
  56.  
  57. for operator in operators:
  58.     text, row, column = operator
  59.     if text == "=":
  60.         tk.Button(window, text=text, width=5, height=2, command=button_equal).grid(row=row, column=column)
  61.     elif text == "C":
  62.         tk.Button(window, text=text, width=5, height=2, command=button_clear).grid(row=row, column=column)
  63.     else:
  64.         tk.Button(window, text=text, width=5, height=2, command=lambda t=text: button_click(t)).grid(row=row, column=column)
  65.  
  66. window.mainloop()
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement