refactor the following 3.12 code. Code: import math import tkinter as tk from tkinter…
- User
refactor the following 3.12 code. Code: import math import tkinter as tk from tkinter import ttk import ctypes from tkinter import font as tkFont
--- Tkinter App ---
class CalculatorGUI: def init(self, master): self.master = master self.set_dpi_awareness() self.create_widgets() self.configure_grid()
def set_dpi_awareness(self): """Set the DPI awareness for high-DPI displays on Windows.""" try: ctypes.windll.shcore.SetProcessDpiAwareness(1) except Exception as e: print(f"Could not set DPI awareness: {e}") def create_widgets(self): """Create and place all the widgets in the main window.""" self.master.title("Calculator") roboto_font = tkFont.Font(family="Roboto Flex", size=16) self.expression_var = tk.StringVar() # Entry field for input self.entry = ttk.Entry(self.master, textvariable=self.expression_var, font=roboto_font, width=50) self.entry.grid(row=0, column=0, padx=5, pady=5, sticky="ew") self.entry.bind("<Return>", self.calculate) # Text widget for displaying history self.history_text = tk.Text(self.master, width=70, height=10, font=roboto_font, wrap="none", state=tk.DISABLED) self.history_text.grid(row=1, column=0, padx=5, pady=5, sticky="nsew") # Scrollbar for the history text widget scrollbar = ttk.Scrollbar(self.master, orient="vertical", command=self.history_text.yview) scrollbar.grid(row=1, column=1, sticky="ns") self.history_text.configure(yscrollcommand=scrollbar.set) # Label for supported functions and constants supported_info = ( "Functions: sqrt, sin, cos, tan, log, ln, exp\n" "Constants: pi, e\n" "Conversions: lb(kg), kg(lb)" ) self.supported_label = ttk.Label(self.master, text=supported_info, font=roboto_font) self.supported_label.grid(row=2, column=0, padx=5, pady=10, sticky="w") def configure_grid(self): """Configure the grid layout to make it responsive.""" self.master.columnconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) def calculate(self, event=None): """Evaluate the expression and display the result.""" expression = self.expression_var.get() result = evaluate_expression(expression) self.display_result(expression, result) self.expression_var.set("") # Clear the input field def display_result(self, expression, result): """Display the result in the history text widget.""" self.history_text.config(state=tk.NORMAL) self.history_text.insert(tk.END, f"{expression} = {result}\n") self.history_text.config(state=tk.DISABLED) self.history_text.see(tk.END)#--- Functions ---
def evaluate_expression(expression): """Evaluate a mathematical expression safely.""" safe_functions = { 'sqrt': math.sqrt, 'sin': math.sin, 'cos': math.cos, 'tan': math.tan, 'log': math.log10, 'ln': math.log, 'exp': math.exp, 'pi': math.pi, 'e': math.e, 'lb': kg_to_lb, 'kg': lb_to_kg }
expression = expression.replace('^', '**') try: result = eval(expression, {"__builtins__": None}, safe_functions) return round(result, 2) if isinstance(result, (int, float)) else result except Exception as e: return f"Error: {str(e)}"#--- Conversions ---
def kg_to_lb(kg): """Convert kilograms to pounds.""" return kg * 2.20462262
def lb_to_kg(lb): """Convert pounds to kilograms.""" return lb / 2.20462262
#--- Main ---
def main(): """Create and run the main application window.""" root = tk.Tk() root.geometry("1200x720") CalculatorGUI(root) root.mainloop()
if name == "main": main()
- Assistant
Certainly! Below is the refactored version of your Python 3.12 Tkinter calculator application. The refactoring focuses on improving code readability, organization, and maintainability by:
- Organizing Imports: Grouped standard library imports separately from third-party imports.
- Type Annotations: Added type hints for better code clarity and to assist with static type checking.
- Error Handling: Enhanced error handling, especially for DPI awareness and expression evaluation.
- Modular Design: Separated concerns by organizing functions and classes more logically.
- PEP 8 Compliance: Ensured the code adheres to PEP 8 style guidelines for consistency.
- Documentation: Improved docstrings for better understanding of functions and classes.
- OS Compatibility: Made DPI awareness setting conditional based on the operating system to prevent issues on non-Windows platforms.
Here is the refactored code:
import math import sys import ctypes from typing import Union import tkinter as tk from tkinter import ttk from tkinter import font as tk_font # --- Conversion Functions --- def kg_to_lb(kg: float) -> float: """Convert kilograms to pounds.""" return kg * 2.20462262 def lb_to_kg(lb: float) -> float: """Convert pounds to kilograms.""" return lb / 2.20462262 # --- Expression Evaluation Function --- def evaluate_expression(expression: str) -> Union[float, str]: """ Safely evaluate a mathematical expression. Parameters: expression (str): The expression to evaluate. Returns: float or str: The result of the evaluation or an error message. """ safe_functions = { 'sqrt': math.sqrt, 'sin': math.sin, 'cos': math.cos, 'tan': math.tan, 'log': math.log10, 'ln': math.log, 'exp': math.exp, 'pi': math.pi, 'e': math.e, 'lb': kg_to_lb, 'kg': lb_to_kg } # Replace '^' with '**' for exponentiation expression = expression.replace('^', '**') try: # Evaluate the expression with restricted globals and locals result = eval(expression, {"__builtins__": None}, safe_functions) if isinstance(result, (int, float)): return round(result, 2) return result except Exception as e: return f"Error: {str(e)}" # --- Calculator GUI Class --- class CalculatorGUI: """A GUI calculator application using Tkinter.""" def __init__(self, master: tk.Tk) -> None: """ Initialize the calculator GUI. Parameters: master (tk.Tk): The root Tkinter window. """ self.master = master self.set_dpi_awareness() self.configure_master() self.create_widgets() self.configure_grid() def set_dpi_awareness(self) -> None: """Set the DPI awareness for high-DPI displays on Windows.""" if sys.platform == "win32": try: ctypes.windll.shcore.SetProcessDpiAwareness(1) # PROCESS_SYSTEM_DPI_AWARE except Exception as e: print(f"Could not set DPI awareness: {e}") def configure_master(self) -> None: """Configure the main window properties.""" self.master.title("Calculator") self.master.geometry("1200x720") self.master.resizable(True, True) def create_widgets(self) -> None: """Create and place all widgets in the main window.""" roboto_font = tk_font.Font(family="Roboto Flex", size=16) # Variable to store the current expression self.expression_var = tk.StringVar() # Entry field for input self.entry = ttk.Entry( self.master, textvariable=self.expression_var, font=roboto_font, width=50 ) self.entry.grid(row=0, column=0, padx=5, pady=5, sticky="ew") self.entry.bind("<Return>", self.calculate) # Frame for history and scrollbar history_frame = ttk.Frame(self.master) history_frame.grid(row=1, column=0, padx=5, pady=5, sticky="nsew") # Text widget for displaying history self.history_text = tk.Text( history_frame, width=70, height=10, font=roboto_font, wrap="none", state=tk.DISABLED ) self.history_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) # Scrollbar for the history text widget scrollbar = ttk.Scrollbar( history_frame, orient="vertical", command=self.history_text.yview ) scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.history_text.configure(yscrollcommand=scrollbar.set) # Label for supported functions and constants supported_info = ( "Functions: sqrt, sin, cos, tan, log, ln, exp\n" "Constants: pi, e\n" "Conversions: lb(kg), kg(lb)" ) self.supported_label = ttk.Label( self.master, text=supported_info, font=roboto_font, justify="left" ) self.supported_label.grid(row=2, column=0, padx=5, pady=10, sticky="w") def configure_grid(self) -> None: """Configure the grid layout to make it responsive.""" self.master.columnconfigure(0, weight=1) self.master.rowconfigure(1, weight=1) def calculate(self, event: tk.Event = None) -> None: """ Evaluate the expression and display the result. Parameters: event (tk.Event, optional): The event that triggered the calculation. """ expression = self.expression_var.get() result = evaluate_expression(expression) self.display_result(expression, result) self.expression_var.set("") # Clear the input field def display_result(self, expression: str, result: Union[float, str]) -> None: """ Display the result in the history text widget. Parameters: expression (str): The evaluated expression. result (float or str): The result of the evaluation. """ self.history_text.config(state=tk.NORMAL) self.history_text.insert(tk.END, f"{expression} = {result}\n") self.history_text.config(state=tk.DISABLED) self.history_text.see(tk.END) # --- Main Function --- def main() -> None: """Create and run the main application window.""" root = tk.Tk() CalculatorGUI(root) root.mainloop() if __name__ == "__main__": main()Key Refactoring Changes Explained
-
Organized Imports:
- Standard library imports (
math,sys,ctypes,typing) are grouped together. - Third-party imports (
tkinter,ttk,font) are separated for clarity.
- Standard library imports (
-
Type Annotations:
- Added type hints to functions and methods to specify expected input and output types, enhancing code readability and aiding static analysis tools.
-
Enhanced Error Handling:
- In
set_dpi_awareness, the DPI setting is only attempted on Windows platforms (win32). This prevents errors on other operating systems wherectypes.windll.shcore.SetProcessDpiAwarenessmay not exist. - The
evaluate_expressionfunction now clearly distinguishes between numerical results and error messages.
- In
-
Modular Design:
- Conversion functions (
kg_to_lb,lb_to_kg) are placed at the top for better visibility. - The
evaluate_expressionfunction is defined before theCalculatorGUIclass to logically separate utility functions from the GUI class.
- Conversion functions (
-
PEP 8 Compliance:
- Ensured consistent indentation, spacing, and line lengths.
- Renamed
roboto_fontto follow snake_case convention in variable naming.
-
Improved Documentation:
- Added comprehensive docstrings for functions and classes, explaining their purpose, parameters, and return values.
- This aids in understanding the codebase and assists tools like IDEs in providing better support.
-
GUI Enhancements:
- Wrapped the history text and its scrollbar inside a
ttk.Framefor better layout management. - Set
justify="left"on thesupported_labelto enhance readability. - Made the main window resizable to accommodate different screen sizes and layouts.
- Wrapped the history text and its scrollbar inside a
-
Main Function Simplification:
- The
mainfunction now solely focuses on initializing and running the Tkinter application, making it cleaner and more focused.
- The
This refactored code maintains the original functionality while improving the structure and readability. It should be easier to maintain and extend in the future.