Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions calc.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import tkinter as tk
import math # Importing math for factorial function

LARGE_FONT_STYLE = ("Arial", 40, "bold")
SMALL_FONT_STYLE = ("Arial", 16)
Expand Down Expand Up @@ -56,6 +57,7 @@ def create_special_buttons(self):
self.create_equals_button()
self.create_square_button()
self.create_sqrt_button()
self.create_factorial_button() # Add factorial button

def create_display_labels(self):
total_label = tk.Label(self.display_frame, text=self.total_expression, anchor=tk.E, bg=LIGHT_GRAY,
Expand Down Expand Up @@ -110,7 +112,10 @@ def create_clear_button(self):
button.grid(row=0, column=1, sticky=tk.NSEW)

def square(self):
self.current_expression = str(eval(f"{self.current_expression}**2"))
try:
self.current_expression = str(eval(f"{self.current_expression}**2"))
except:
self.current_expression = "Error"
self.update_label()

def create_square_button(self):
Expand All @@ -119,20 +124,38 @@ def create_square_button(self):
button.grid(row=0, column=2, sticky=tk.NSEW)

def sqrt(self):
self.current_expression = str(eval(f"{self.current_expression}**0.5"))
try:
self.current_expression = str(eval(f"{self.current_expression}**0.5"))
except:
self.current_expression = "Error"
self.update_label()

def create_sqrt_button(self):
button = tk.Button(self.buttons_frame, text="\u221ax", bg=OFF_WHITE, fg=LABEL_COLOR, font=DEFAULT_FONT_STYLE,
borderwidth=0, command=self.sqrt)
button.grid(row=0, column=3, sticky=tk.NSEW)

def factorial(self):
try:
value = int(float(self.current_expression))
if value < 0:
self.current_expression = "Error"
else:
self.current_expression = str(math.factorial(value))
except:
self.current_expression = "Error"
self.update_label()

def create_factorial_button(self):
button = tk.Button(self.buttons_frame, text="x!", bg=OFF_WHITE, fg=LABEL_COLOR,
font=DEFAULT_FONT_STYLE, borderwidth=0, command=self.factorial)
button.grid(row=0, column=0, sticky=tk.NSEW)

def evaluate(self):
self.total_expression += self.current_expression
self.update_total_label()
try:
self.current_expression = str(eval(self.total_expression))

self.total_expression = ""
except Exception as e:
self.current_expression = "Error"
Expand Down