You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.7 KiB
57 lines
1.7 KiB
import tkinter as tk
|
|
from tkinter import messagebox
|
|
|
|
def on_click(event):
|
|
text = event.widget.cget("text")
|
|
if text == "=":
|
|
calculate_result()
|
|
elif text == "C":
|
|
clear_entry()
|
|
else:
|
|
entry_var.set(entry_var.get() + text)
|
|
|
|
def calculate_result(event=None):
|
|
try:
|
|
result = eval(str(entry.get()))
|
|
result = round(float(result), 2) # Format to 2 decimal places
|
|
entry_var.set(f"{result:.2f}")
|
|
except Exception as e:
|
|
messagebox.showerror("Error", f"Invalid Expression: {e}")
|
|
|
|
def clear_entry(event=None):
|
|
entry_var.set("")
|
|
return "break" # Prevents default behavior of inserting 'c' or 'C'
|
|
|
|
# Main window
|
|
root = tk.Tk()
|
|
root.title("Bobs Calc")
|
|
root.geometry("215x250")
|
|
|
|
entry_var = tk.StringVar()
|
|
entry = tk.Entry(root, textvariable=entry_var, font="Arial 20")
|
|
entry.pack(fill=tk.BOTH, ipadx=8, pady=10, padx=10)
|
|
entry.focus_set() # Set focus to the entry widget
|
|
entry.bind("<Return>", calculate_result) # Bind Enter key to calculate_result
|
|
entry.bind("<KP_Enter>", calculate_result) # Bind NumPad Enter key
|
|
entry.bind("<c>", clear_entry) # Bind 'c' key to clear_entry
|
|
entry.bind("<C>", clear_entry) # Bind 'C' key to clear_entry
|
|
|
|
button_frame = tk.Frame(root)
|
|
button_frame.pack()
|
|
|
|
buttons = [
|
|
["7", "8", "9", "/"],
|
|
["4", "5", "6", "*"],
|
|
["1", "2", "3", "-"],
|
|
["C", "0", "=", "+"]
|
|
]
|
|
|
|
for row in buttons:
|
|
row_frame = tk.Frame(button_frame)
|
|
row_frame.pack(expand=True, fill="both")
|
|
for btn_text in row:
|
|
btn = tk.Button(row_frame, text=btn_text, font="Arial 18", relief=tk.RAISED)
|
|
btn.pack(side=tk.LEFT, expand=True, fill="both")
|
|
btn.bind("<Button-1>", on_click)
|
|
|
|
root.mainloop()
|
|
|