Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as tk
- # Initialize the window
- window = tk.Tk()
- window.title("Calculator")
- # Entry widget to display and input numbers
- entry = tk.Entry(window, width=25, font=("Arial", 12))
- entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
- # Function to handle button clicks
- def button_click(number):
- current = entry.get()
- entry.delete(0, tk.END)
- entry.insert(tk.END, current + str(number))
- def button_clear():
- entry.delete(0, tk.END)
- def button_equal():
- try:
- result = eval(entry.get())
- entry.delete(0, tk.END)
- entry.insert(tk.END, result)
- except Exception:
- entry.delete(0, tk.END)
- entry.insert(tk.END, "Error")
- # Create number buttons
- 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, 0),
- ]
- for button in buttons:
- text, row, column = button
- tk.Button(window, text=text, width=5, height=2, command=lambda t=text: button_click(t)).grid(row=row, column=column)
- # Create operator buttons
- operators = [
- ("+", 1, 3),
- ("-", 2, 3),
- ("*", 3, 3),
- ("/", 4, 3),
- ("=", 4, 2),
- ("C", 4, 1),
- ]
- for operator in operators:
- text, row, column = operator
- if text == "=":
- tk.Button(window, text=text, width=5, height=2, command=button_equal).grid(row=row, column=column)
- elif text == "C":
- tk.Button(window, text=text, width=5, height=2, command=button_clear).grid(row=row, column=column)
- else:
- tk.Button(window, text=text, width=5, height=2, command=lambda t=text: button_click(t)).grid(row=row, column=column)
- window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement