Implement a gui feature so that the user can click on a function and it is copied in the execution field. Implement buttons to do this order the buttons in a matrix row 1 (Functions, Conversions, Unique, Constants) in the rows below order in the buttons. adjust the size so that it covers the size of the textfield. Keep all buttons at the same size. Print the new code in full. Think step by step. Code: import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
--- Revised Function for Capitalization ---
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
--- Conversion Functions ---
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
--- Evaluation Function ---
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"builtins": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"builtins": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
--- Calculator GUI Class ---
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
To implement the GUI feature you described, we will add buttons to the calculator application that allow users to click on function buttons. When clicked, these buttons will insert the corresponding function into the execution field (text entry widget). We'll organize these function buttons into a matrix structure as requested.
Here is an updated version of your calculator application that includes these features:
python
User
Good now delete the text (Constants, ...) since it is not nessecary anymore
Assistant
Sure, let's update the code by removing the static text label that lists the functions and constants, as it is now redundant due to the dynamic buttons. Here is the modified code:
python
User
Now order the buttons nex to each other first column Functions and its buttons two buttons per row. second column Conversions and its buttons two buttons per row. Third column Unique and its buttons two buttons per row. Fourth constants and its buttons two buttons per row. adjust the spacing so that it covers the whole wide of the textfield
Assistant
To achieve the layout you described, we can organize the buttons into columns that align beneath their respective category titles. Each category will display its buttons in two rows per category, displayed next to each other, accounting for uniform spacing so that they span the width of the text field.
Here's the modified code to reflect these requirements:
python
User
Good but now some of the buttons are missing and it does not use two buttons per column. What i mean with that is for Example column 1 row 1 (Functions) column 1 row 2 (sin, cos) the cos botton should be next to the sin button bellow the functions text.
Assistant
Sure! Let's adjust the layout so that each category's title appears at the top of its respective column, and the buttons are organized into rows two at a time, directly beneath each category title. Here's how you can achieve that layout:
python
User
nothing changed. To make it clearer have two columns for each category. So you can have two buttons next to each other in each categoriy.
Assistant
I apologize for the oversight. Let’s organize the buttons so that each category title is followed by two columns for the buttons, allowing two buttons per row under each category. Here's how you can structure that:
python
User
good now increase the font size to 12 and make sure roboto flex is used like in the rest of the gui
Assistant
To ensure that the buttons use the same font and size as the rest of the GUI, we can explicitly set the font to "Roboto Flex" with a size of 12 when creating the buttons. Here's how you can adjust the code to achieve this:
python
User
add a fith category next to Constants called Settings. Put the Randians/Degres button under this categoriy and adjust its size in accordance with the other buttons
Assistant
To add a fifth category called "Settings" and include the "Radians/Degrees" toggle button under this category, we'll adjust the layout to accommodate the new category while maintaining consistency with existing button sizes and styles. Here's the updated code:
python
User
modify the code so that all categories only have one column for the buttons except the functions category which should now have three.
Assistant
To meet the new requirements where the "Functions" category has three columns for buttons, while all other categories (including "Conversions", "Unique", "Constants", and "Settings") have just one column, I'll update the layout accordingly. Here's how you can adjust the code:
python
User
add an equal amount of space between each category. Add the space so that all five categories combined perfectly fill the same size as the textfield.
Assistant
To evenly distribute the categories so that they span the width of the text field with equal spacing between them, we need to adjust the layout to consider both the column width for the buttons and the space between categories.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
self.create_toggle_button()
supported_info: str = (
"Constants: pi, e\n"
"Functions: sqrt, sin, cos, tan, asin, acos, atan, log, ln\n"
"Conversions: lb(kg), kg(lb)\n"
"Unique: capitalize\n"
)
self.supported_label: ttk.Label = ttk.Label(
self.master, text=supported_info, font=self.font, justify=tk.LEFT
)
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
row = 0
for category, funcs in self.function_buttons.items():
col = 0
category_label = ttk.Label(self.function_frame, text=category)
category_label.grid(row=row, column=col, padx=5, pady=5, sticky="w")
row += 1
for func in funcs:
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10
)
button.grid(row=row, column=col, padx=5, pady=5)
col += 1
if col >= 4: # Max four buttons per row
col = 0
row += 1
row += 1
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self) -> None:
"""Create the Degrees/Radians toggle button."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.font, padding=0)
self.mode_button: ttk.Button = ttk.Button(
self.master,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=2, padx=(0, 5), pady=5, sticky="ns")
self.mode_button.grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.supported_label.grid(row=2, column=1, padx=5, pady=10, sticky="w")
self.function_frame.grid(row=3, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Changes:
Function Buttons: Added function buttons organized into categories ("Functions", "Conversions", "Unique", "Constants"). These buttons are created dynamically based on the available functions and constants.
Command Integration: When a button is clicked, the corresponding function name is inserted into the text entry field with parentheses for function arguments.
Button Layout: Function buttons are arranged in a grid format within a separate frame for better organization.
This adapts the existing calculator to include the new feature, while maintaining code readability and functionality.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
self.create_toggle_button()
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
row = 0
for category, funcs in self.function_buttons.items():
col = 0
category_label = ttk.Label(self.function_frame, text=category)
category_label.grid(row=row, column=col, padx=5, pady=5, sticky="w")
row += 1
for func in funcs:
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10
)
button.grid(row=row, column=col, padx=5, pady=5)
col += 1
if col >= 4: # Max four buttons per row
col = 0
row += 1
row += 1
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self) -> None:
"""Create the Degrees/Radians toggle button."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.font, padding=0)
self.mode_button: ttk.Button = ttk.Button(
self.master,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=2, padx=(0, 5), pady=5, sticky="ns")
self.mode_button.grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.function_frame.grid(row=3, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Changes:
Removed the static text label self.supported_label from create_widgets() and the related layout logic in layout_widgets().
The dynamic category labels in the create_function_buttons() method now serve to provide users with necessary information about functions and constants directly above the corresponding buttons.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
self.create_toggle_button()
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
column_index = 0
for category, funcs in self.function_buttons.items():
ttk.Label(self.function_frame, text=category).grid(
row=0, column=column_index, padx=5, pady=5, sticky="n"
)
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=15
)
button.grid(row=(i//2) + 1, column=column_index, padx=5, pady=5)
column_index += 1
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self) -> None:
"""Create the Degrees/Radians toggle button."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.font, padding=0)
self.mode_button: ttk.Button = ttk.Button(
self.master,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=2, padx=(0, 5), pady=5, sticky="ns")
self.mode_button.grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.function_frame.grid(row=3, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Layout Adjustments:
Each function category and its buttons are allocated to a specific column.
Buttons within each category are placed in two-button rows.
Adjusted button width to 15 to ensure they cover the width equally when placed together across four columns.
Each category name is displayed at the top of its column to clearly indicate the type of functions or constants.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
self.create_toggle_button()
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
for col, (category, funcs) in enumerate(self.function_buttons.items()):
ttk.Label(self.function_frame, text=category).grid(
row=0, column=col, padx=5, pady=5, sticky="n"
)
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=15
)
button.grid(row=(i % 2) + 1, column=col, padx=5, pady=5)
col += 1
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self) -> None:
"""Create the Degrees/Radians toggle button."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.font, padding=0)
self.mode_button: ttk.Button = ttk.Button(
self.master,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=2, padx=(0, 5), pady=5, sticky="ns")
self.mode_button.grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.function_frame.grid(row=3, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Changes:
Each category now has a label in the first row in its column.
Buttons are now placed two per row under each category title. The column index (col) determines which category the buttons are under.
Adjusted button configuration to ensure a consistent look and ensure they span the width below each category.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
self.create_toggle_button()
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
col = 0
for category, funcs in self.function_buttons.items():
ttk.Label(self.function_frame, text=category).grid(
row=0, column=col, columnspan=2, padx=5, pady=5, sticky="n"
)
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10
)
button.grid(row=(i // 2) + 1, column=col + (i % 2), padx=5, pady=5)
col += 2 # Move to the next set of columns for the next category
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self) -> None:
"""Create the Degrees/Radians toggle button."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.font, padding=0)
self.mode_button: ttk.Button = ttk.Button(
self.master,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=2, padx=(0, 5), pady=5, sticky="ns")
self.mode_button.grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.function_frame.grid(row=3, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Changes:
Each category's label now spans two columns (columnspan=2), aligning above its buttons.
Buttons are aligned in two columns below each category, with the logic (i // 2) determining the row and (i % 2) alternating between the left and right positions in each row.
Increment the column index by 2 after each category to ensure the correct layout across categories.
This setup ensures your buttons are displayed in a clear, organized manner within each category, using the full width beneath the entry field.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.button_font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=12)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
self.create_toggle_button()
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
col = 0
for category, funcs in self.function_buttons.items():
ttk.Label(self.function_frame, text=category, font=self.button_font).grid(
row=0, column=col, columnspan=2, padx=5, pady=5, sticky="n"
)
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10,
style='Function.TButton'
)
button.grid(row=(i // 2) + 1, column=col + (i % 2), padx=5, pady=5)
col += 2 # Move to the next set of columns for the next category
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self) -> None:
"""Create the Degrees/Radians toggle button."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.font, padding=0)
style.configure('Function.TButton', font=self.button_font) # Set style for function buttons
self.mode_button: ttk.Button = ttk.Button(
self.master,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=2, padx=(0, 5), pady=5, sticky="ns")
self.mode_button.grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.function_frame.grid(row=3, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Explanation of Changes:
Added self.button_font to store the font configuration specifically for the buttons, setting it to "Roboto Flex" with size 12.
Applied this font to all button labels and buttons themselves by specifying font=self.button_font.
Ensured the button style consistently uses the defined font.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.button_font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=12)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
col = 0
for category, funcs in self.function_buttons.items():
ttk.Label(self.function_frame, text=category, font=self.button_font).grid(
row=0, column=col, columnspan=2, padx=5, pady=5, sticky="n"
)
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10,
style='Function.TButton'
)
button.grid(row=(i // 2) + 1, column=col + (i % 2), padx=5, pady=5)
col += 2 # Move to the next set of columns for the next category
# Add the Settings category with the Radians/Degrees button
settings_col = col
ttk.Label(self.function_frame, text="Settings", font=self.button_font).grid(
row=0, column=settings_col, columnspan=2, padx=5, pady=5, sticky="n"
)
self.create_toggle_button(settings_col)
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self, col: int) -> None:
"""Create the Degrees/Radians toggle button in the settings column."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.button_font, padding=0)
style.configure('Function.TButton', font=self.button_font) # Set style for function buttons
self.mode_button: ttk.Button = ttk.Button(
self.function_frame,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
width=10
)
self.mode_button.grid(row=1, column=col, padx=5, pady=5, columnspan=2)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=4, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=3, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=3, padx=(0, 5), pady=5, sticky="ns")
self.function_frame.grid(row=2, column=0, columnspan=4, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Adjustments:
Added a "Settings" category label next to "Constants."
Placed the "Radians/Degrees" toggle button under the "Settings" category.
Adjusted the placement of the toggle button to align with the layout of other buttons and set the button's font and size accordingly.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.button_font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=12)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=50
)
self.entry.bind("<Return>", self.calculate)
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
# Functions category with three columns
ttk.Label(self.function_frame, text="Functions", font=self.button_font).grid(
row=0, column=0, columnspan=3, padx=5, pady=5, sticky="n"
)
funcs = self.function_buttons["Functions"]
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10,
style='Function.TButton'
)
button.grid(row=(i // 3) + 1, column=(i % 3), padx=5, pady=5)
# Other categories with one column each
col = 0
for category in ["Conversions", "Unique", "Constants"]:
col += 3
ttk.Label(self.function_frame, text=category, font=self.button_font).grid(
row=0, column=col, padx=5, pady=5, sticky="n"
)
funcs = self.function_buttons[category]
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10,
style='Function.TButton'
)
button.grid(row=i + 1, column=col, padx=5, pady=5)
# Add the Settings category with the Radians/Degrees button
col += 1
ttk.Label(self.function_frame, text="Settings", font=self.button_font).grid(
row=0, column=col, padx=5, pady=5, sticky="n"
)
self.create_toggle_button(col)
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self, col: int) -> None:
"""Create the Degrees/Radians toggle button in the settings column."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.button_font, padding=0)
style.configure('Function.TButton', font=self.button_font) # Set style for function buttons
self.mode_button: ttk.Button = ttk.Button(
self.function_frame,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
width=10
)
self.mode_button.grid(row=1, column=col, padx=5, pady=5)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=5, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=4, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=4, padx=(0, 5), pady=5, sticky="ns")
self.function_frame.grid(row=2, column=0, columnspan=5, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Adjustments:
The "Functions" category now uses three columns, with buttons arranged in rows of three.
Each of the other categories ("Conversions", "Unique", "Constants", "Settings") are setup with single columns for buttons.
Adjusted the placements and layout logic to ensure clarity and usability.
import ctypes
import math
import re
from typing import Any, Dict, Union
import tkinter as tk
from tkinter import font as tkFont, ttk
# Revised Function for Capitalization
def capitalize_sentence(sentence: str) -> str:
"""Capitalize the first letter of each word in the sentence."""
return ' '.join(word[0].upper() + word[1:].lower() for word in sentence.split())
# Conversion Functions
def kg_to_lb(kg: float) -> float:
"""Convert kilograms to pounds."""
return kg / 0.45359237
def lb_to_kg(lb: float) -> float:
"""Convert pounds to kilograms."""
return lb * 0.45359237
# Evaluation Function
def evaluate_expression(expression: str, use_degrees: bool = False) -> Union[float, str]:
"""Safely evaluate a mathematical expression considering degree mode."""
def convert_angle(func: Any, x: float) -> float:
return func(math.radians(x)) if use_degrees else func(x)
def inverse_convert_angle(func: Any, x: float) -> float:
result = func(x)
return math.degrees(result) if use_degrees else result
safe_functions: Dict[str, Any] = {
"sqrt": math.sqrt,
"sin": lambda x: convert_angle(math.sin, x),
"cos": lambda x: convert_angle(math.cos, x),
"tan": lambda x: convert_angle(math.tan, x),
"asin": lambda x: inverse_convert_angle(math.asin, x),
"acos": lambda x: inverse_convert_angle(math.acos, x),
"atan": lambda x: inverse_convert_angle(math.atan, x),
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"lb": kg_to_lb,
"kg": lb_to_kg,
"capitalize": capitalize_sentence # Updated to handle entire sentences
}
expression = expression.replace("^", "**")
expression = re.sub(r'\bcapitalize\((\w+)\)', r'capitalize("\1")', expression)
func_calls = re.findall(r"(\b\w+\b)\(([^)]+)\)", expression)
for func, arg in func_calls:
if func in ["asin", "acos"]:
try:
value = eval(arg, {"__builtins__": None}, safe_functions)
if not -1 <= value <= 1:
raise ValueError(f"{func}(x) is undefined for |x| > 1")
except Exception as e:
return f"Error: {e}"
try:
result = eval(expression, {"__builtins__": None}, safe_functions)
if isinstance(result, float) and abs(result) < 1e-10:
result = 0.0
return round(result, 2) if isinstance(result, (int, float)) else result
except Exception as e:
return f"Error: {e}"
# Calculator GUI Class
class CalculatorGUI:
"""Tkinter-based Calculator with Degrees/Radians toggle and history."""
def __init__(self, master: tk.Tk) -> None:
self.master = master
self.use_degrees: tk.BooleanVar = tk.BooleanVar(value=False)
self.set_dpi_awareness()
self.setup_window()
self.create_widgets()
self.layout_widgets()
self.configure_grid()
def set_dpi_awareness(self) -> None:
"""Enable high-DPI support on Windows."""
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
pass
def setup_window(self) -> None:
"""Configure the main application window."""
self.master.title("Calculator")
self.master.geometry("1200x720")
def create_widgets(self) -> None:
"""Initialize all GUI components."""
self.font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=16)
self.button_font: tkFont.Font = tkFont.Font(family="Roboto Flex", size=12)
self.expression_var: tk.StringVar = tk.StringVar()
self.entry: ttk.Entry = ttk.Entry(
self.master, textvariable=self.expression_var, font=self.font, width=60
)
self.entry.grid(padx=10) # Adjust width to match buttons frame
self.history_text: tk.Text = tk.Text(
self.master,
width=70,
height=10,
font=self.font,
wrap="none",
state=tk.DISABLED,
)
self.scrollbar: ttk.Scrollbar = ttk.Scrollbar(
self.master, orient="vertical", command=self.history_text.yview
)
self.history_text.configure(yscrollcommand=self.scrollbar.set)
# Create buttons for functions
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = ttk.Frame(self.master)
self.create_function_buttons()
def create_function_buttons(self):
"""Create buttons for inserting functions into the entry."""
pad_x = 10 # Padding for equal space distribution
col = 0
# Functions category with three columns
ttk.Label(self.function_frame, text="Functions", font=self.button_font).grid(
row=0, column=col, columnspan=3, padx=pad_x, pady=5, sticky="n"
)
funcs = self.function_buttons["Functions"]
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10,
style='Function.TButton'
)
button.grid(row=(i // 3) + 1, column=(i % 3), padx=pad_x, pady=5)
# Other categories each with one column
col = 3 # Start new block for other categories
for category in ["Conversions", "Unique", "Constants"]:
col += 1
ttk.Label(self.function_frame, text=category, font=self.button_font).grid(
row=0, column=col, padx=pad_x, pady=5, sticky="n"
)
funcs = self.function_buttons[category]
for i, func in enumerate(funcs):
button = ttk.Button(
self.function_frame,
text=func,
command=lambda f=func: self.insert_function(f),
width=10,
style='Function.TButton'
)
button.grid(row=i + 1, column=col, padx=pad_x, pady=5)
# Settings category with Radians/Degrees button
col += 1
ttk.Label(self.function_frame, text="Settings", font=self.button_font).grid(
row=0, column=col, padx=pad_x, pady=5, sticky="n"
)
self.create_toggle_button(col)
def insert_function(self, function: str) -> None:
"""Insert function text into the expression entry."""
current_text = self.expression_var.get()
new_text = f"{current_text}{function}()"
self.expression_var.set(new_text)
self.entry.icursor(len(new_text) - 1) # Move the cursor inside the parentheses
def create_toggle_button(self, col: int) -> None:
"""Create the Degrees/Radians toggle button in the settings column."""
style: ttk.Style = ttk.Style()
style.configure("ToggleButton.TButton", font=self.button_font, padding=0)
style.configure('Function.TButton', font=self.button_font) # Set style for function buttons
self.mode_button: ttk.Button = ttk.Button(
self.function_frame,
text="Radians",
command=self.toggle_mode,
style="ToggleButton.TButton",
width=10
)
self.mode_button.grid(row=1, column=col, padx=10, pady=5)
def layout_widgets(self) -> None:
"""Arrange widgets within the window."""
self.entry.grid(row=0, column=0, columnspan=5, padx=5, pady=5, sticky="ew")
self.history_text.grid(row=1, column=0, columnspan=4, padx=5, pady=5, sticky="nsew")
self.scrollbar.grid(row=1, column=4, padx=(0, 5), pady=5, sticky="ns")
self.function_frame.grid(row=2, column=0, columnspan=5, padx=5, pady=5, sticky="ew")
def configure_grid(self) -> None:
"""Make the grid layout responsive."""
self.master.columnconfigure(0, weight=1)
self.master.columnconfigure(1, weight=0)
self.master.rowconfigure(1, weight=1)
def toggle_mode(self) -> None:
"""Switch between Degrees and Radians modes."""
if self.use_degrees.get():
self.use_degrees.set(False)
self.mode_button.config(text="Radians")
else:
self.use_degrees.set(True)
self.mode_button.config(text="Degrees")
def calculate(self, event: tk.Event = None) -> None:
"""Evaluate the expression and update history."""
expression: str = self.expression_var.get().strip()
if not expression:
return
result: Union[float, str] = evaluate_expression(
expression, use_degrees=self.use_degrees.get()
)
self.display_result(expression, result)
self.expression_var.set("")
def display_result(self, expression: str, result: Union[float, str]) -> None:
"""Append the calculation to the history log."""
self.history_text.config(state=tk.NORMAL)
mode: str = "Degrees" if self.use_degrees.get() else "Radians"
self.history_text.insert(tk.END, f"[{mode}] {expression} = {result}\n")
self.history_text.config(state=tk.DISABLED)
self.history_text.see(tk.END)
# Main Function
def main() -> None:
"""Run the Calculator application."""
root: tk.Tk = tk.Tk()
CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Key Adjustments:
Added horizontal padding (pad_x = 10) to create equal spacing between categories.
Ensured that the overall widths of buttons and spaces align with the width of the text field.
Adjusted column indices to ensure that categories are spaced evenly within the grid system.
This approach distributes categories across the frame evenly, matching the width of the text entry field.