Certainly! Below is the refactored Python 3.12 code that replaces PySide6 with Tkinter. This version maintains the original functionality, including mathematical calculations, conversions, text processing, history management, variable storage, and data persistence. Additionally, custom widgets like the LongPressButton have been implemented using Tkinter's event bindings.
import json
import math
import os
import re
import threading
import time
from pathlib import Path
from tkinter import (
Tk, Frame, Grid, Text, Scrollbar, Button, Entry, Label,
END, N, S, E, W, filedialog, messagebox, StringVar
)
# --- Calculations ---
def convert_angle(func, x, use_degrees):
"""Convert angle based on mode (degrees/radians)."""
return func(math.radians(x)) if use_degrees else func(x)
def kilograms_to_pounds(kg):
"""Convert kilograms to pounds."""
return kg / 0.45359237
def pounds_to_kilograms(lb):
"""Convert pounds to kilograms."""
return lb * 0.45359237
def celsius_to_kelvin(c):
"""Convert Celsius to Kelvin."""
return c + 273.15
def kelvin_to_celsius(k):
"""Convert Kelvin to Celsius."""
return k - 273.15
def celsius_to_fahrenheit(c):
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
def fahrenheit_to_celsius(f):
"""Convert Fahrenheit to Celsius."""
return (f - 32) * 5 / 9
def capitalize_sentence(sentence):
"""Capitalize each word in a sentence."""
return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text):
"""Remove duplicate words from text."""
words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split()
return ' '.join(dict.fromkeys(words))
# --- Processing ---
def get_safe_globals(use_degrees, variables):
"""Define safe global functions and variables for expression evaluation."""
trig_funcs = {'sin', 'cos', 'tan', 'asin', 'acos', 'atan'}
safe_globals = {
"sqrt": math.sqrt,
"log": math.log10,
"ln": math.log,
"pi": math.pi,
"e": math.e,
"KilogramToPound": kilograms_to_pounds,
"PoundToKilogram": pounds_to_kilograms,
"CelsiusToKelvin": celsius_to_kelvin,
"KelvinToCelsius": kelvin_to_celsius,
"CelsiusToFahrenheit": celsius_to_fahrenheit,
"FahrenheitToCelsius": fahrenheit_to_celsius,
"capitalize": capitalize_sentence,
"duplicates": remove_duplicates,
}
for func in trig_funcs:
safe_globals[func] = lambda x, f=func: convert_angle(getattr(math, f), x, use_degrees)
safe_globals.update(variables)
return safe_globals
def preprocess_text_functions(expression):
"""Preprocess text functions by ensuring arguments are quoted."""
return re.sub(
r'\b(capitalize|duplicates)\s*\(\s*([^)]+)\s*\)',
lambda m: f'{m.group(1)}("{m.group(2)}")' if not (m.group(2).startswith('"') and m.group(2).endswith('"')) else m.group(0),
expression
)
def validate_inverse_trig(expression, safe_globals):
"""Validate the domain of inverse trig functions."""
for func, arg in re.findall(r'\b(asin|acos)\s*\(\s*([^)]+)\s*\)', expression):
try:
arg_val = eval(arg, {"__builtins__": None}, safe_globals)
if abs(arg_val) > 1:
return f"Error: {func}({arg_val}) is undefined for |{arg_val}| > 1"
except Exception as e:
return f"Error: {e}"
return None
def safe_evaluate(expression, safe_globals):
"""Safely evaluate the mathematical expression."""
try:
result = eval(expression, {"__builtins__": None}, safe_globals)
if isinstance(result, (int, float)):
return format_number(result)
return result
except Exception as e:
return f"Error: {e}"
def format_number(num):
"""Format a number for display."""
if isinstance(num, int):
return str(num) if len(str(abs(num))) <= 9 else f"{num:.3e}"
epsilon = 1e-10
if math.isclose(num, 0.0, abs_tol=epsilon):
return "0"
if math.isclose(num, round(num), abs_tol=epsilon):
return str(int(round(num)))
abs_num = abs(num)
if abs_num >= 1e9 or (abs_num < 1e-6 and abs_num != 0):
return f"{num:.3e}"
return f"{num:.3f}".rstrip('0').rstrip('.')
def evaluate_expression(expression, variables, use_degrees=False):
"""Evaluate the user's expression, handling variable assignments."""
expression = preprocess_text_functions(expression)
base_safe_globals = get_safe_globals(use_degrees, {})
assignment_match = re.match(r'^\s*([a-zA-Z_]\w*)\s*=\s*(.+)$', expression)
if assignment_match:
var_name, var_expr = assignment_match.groups()
if var_name in base_safe_globals:
return f"Error: '{var_name}' is a reserved name and cannot be used as a variable."
safe_globals = get_safe_globals(use_degrees, variables)
var_value = safe_evaluate(var_expr, safe_globals)
if not isinstance(var_value, str) or not var_value.startswith("Error"):
try:
var_value_converted = float(var_value) if '.' in var_value else int(var_value)
variables[var_name] = var_value_converted
return f"{var_name} = {var_value_converted}"
except ValueError:
return f"Error: Cannot assign non-numeric value to variable '{var_name}'"
return var_value
else:
safe_globals = get_safe_globals(use_degrees, variables)
error = validate_inverse_trig(expression, safe_globals)
return error or safe_evaluate(expression, safe_globals)
# --- GUI ---
class LongPressButton(Button):
"""A Tkinter Button that triggers a callback when pressed and held for a specified duration."""
def __init__(self, master, text="", hold_duration=3, command=None, **kwargs):
"""
Initialize the long press button.
:param master: Parent widget.
:param text: Button text.
:param hold_duration: Duration in seconds to trigger the long press.
:param command: Callback function for long press.
:param kwargs: Additional Button options.
"""
super().__init__(master, text=text, command=self.on_click, **kwargs)
self.hold_duration = hold_duration
self.command = command
self.timer = None
self.bind('<ButtonPress-1>', self.on_press)
self.bind('<ButtonRelease-1>', self.on_release)
def on_click(self):
"""Override the default click behavior."""
pass # No action on regular click
def on_press(self, event):
"""Start the timer when the button is pressed."""
self.timer = threading.Timer(self.hold_duration, self.trigger_long_press)
self.timer.start()
def on_release(self, event):
"""Cancel the timer if the button is released before the hold duration."""
if self.timer:
self.timer.cancel()
self.timer = None
def trigger_long_press(self):
"""Invoke the callback for a long press."""
if self.command:
self.command()
class CalculatorGUI:
def __init__(self, root):
self.root = root
self.root.title("Calculator")
self.root.geometry("1280x720")
self.script_dir = Path(__file__).parent
self.use_degrees = True
self.variables = {}
self.history_entries = []
self.text_functions = ['capitalize', 'duplicates']
self.create_widgets()
self.layout_widgets()
self.load_saved_data()
def create_widgets(self):
"""Create all widgets used in the application."""
self.font_family = 'Arial'
self.font_size = 12
# Entry for expression
self.entry_var = StringVar()
self.entry = Entry(self.root, textvariable=self.entry_var, font=(self.font_family, self.font_size))
self.entry.insert(0, 'Enter Expression')
self.entry.bind('<Return>', lambda event: self.calculate())
self.entry.focus_set()
# History Text widget with scrollbar
self.history_frame = Frame(self.root)
self.history_text = Text(self.history_frame, font=(self.font_family, self.font_size), state='disabled', wrap='word')
self.scrollbar = Scrollbar(self.history_frame, command=self.history_text.yview)
self.history_text['yscrollcommand'] = self.scrollbar.set
# Buttons
button_style = {
"font": (self.font_family, self.font_size),
"width": 4,
"height": 2
}
# Search Button
self.search_button = Button(
self.history_frame, text="🔍",
font=(self.font_family, 12),
command=self.toggle_search,
**button_style
)
self.search_button.place(x=0, y=0, width=24, height=24)
# Long Press Delete Button
self.delete_button = LongPressButton(
self.history_frame, text="🗑️",
hold_duration=3,
command=self.clear_history,
font=(self.font_family, 12),
width=4, height=2
)
self.delete_button.place(x=30, y=0, width=24, height=24)
# Variables Button
self.vars_button = Button(
self.history_frame, text="🧮",
font=(self.font_family, 12),
command=self.toggle_vars_overlay,
**button_style
)
self.vars_button.place(x=60, y=0, width=24, height=24)
# Save Button
self.save_button = Button(
self.history_frame, text="💾",
font=(self.font_family, 12),
command=self.save_data,
**button_style
)
self.save_button.place(x=90, y=0, width=24, height=24)
# Load Button
self.load_button = Button(
self.history_frame, text="📂",
font=(self.font_family, 12),
command=self.load_data,
**button_style
)
self.load_button.place(x=120, y=0, width=24, height=24)
# Search Bar
self.search_var = StringVar()
self.search_bar = Entry(
self.history_frame, textvariable=self.search_var, font=(self.font_family, self.font_size)
)
self.search_bar.insert(0, 'Search...')
self.search_bar.bind('<KeyRelease>', lambda event: self.filter_history())
self.search_bar.place(x=150, y=0, width=300, height=24)
self.search_bar.lower() # Hide initially
# Variables Overlay
self.vars_overlay = Entry(
self.history_frame, font=(self.font_family, self.font_size), state='readonly'
)
self.vars_overlay.place(x=460, y=0, width=300, height=24)
self.vars_overlay.lower() # Hide initially
# Variables Delete Button
self.vars_delete_button = LongPressButton(
self.history_frame, text="🗑️",
hold_duration=3,
command=self.clear_variables,
font=(self.font_family, 10),
width=2, height=1
)
self.vars_delete_button.place(x=760, y=0, width=16, height=16)
self.vars_delete_button.lower() # Hide initially
# Function Buttons Frame
self.function_frame = Frame(self.root)
self.create_function_buttons()
def layout_widgets(self):
"""Arrange all widgets in the main window."""
self.entry.pack(padx=10, pady=10, fill='x')
self.history_frame.pack(padx=10, pady=10, fill='both', expand=True)
self.history_text.pack(side='left', fill='both', expand=True)
self.scrollbar.pack(side='right', fill='y')
self.function_frame.pack(padx=10, pady=10, fill='both')
def create_function_buttons(self):
"""Create and arrange function buttons."""
categories = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg", "K", "C", "F", "CF"],
"Text": ["capitalize", "duplicates"],
"Constants": ["pi", "e"],
"Settings": []
}
row = 0
for category, buttons in categories.items():
if category != "Settings":
Label(self.function_frame, text=category, font=(self.font_family, self.font_size, 'bold')).grid(row=row, column=0, columnspan=3, pady=(10, 0))
row += 1
if category == "Functions":
for i, func in enumerate(buttons):
btn = Button(
self.function_frame, text=func, command=lambda f=func: self.insert_function(f, is_text_function=(f in self.text_functions)),
**{"font": (self.font_family, self.font_size), "width": 10, "height": 2}
)
btn.grid(row=row, column=i % 3, padx=5, pady=5)
row += math.ceil(len(buttons) / 3)
elif category == "Conversions":
conversion_mapping = {
"lb": "KilogramToPound",
"kg": "PoundToKilogram",
"K": "CelsiusToKelvin",
"C": "KelvinToCelsius",
"F": "CelsiusToFahrenheit",
"CF": "FahrenheitToCelsius"
}
display_text = {
"lb": "lb(Kg)",
"kg": "kg(lb)",
"K": "K(°C)",
"C": "°C(K)",
"F": "F(°C)",
"CF": "°C(F)"
}
for i, func in enumerate(buttons):
btn = Button(
self.function_frame, text=display_text.get(func, func),
command=lambda f=conversion_mapping.get(func, func): self.insert_function(f, is_text_function=False),
**{"font": (self.font_family, self.font_size), "width": 10, "height": 2}
)
btn.grid(row=row, column=i % 2, padx=5, pady=5)
row += math.ceil(len(buttons) / 2)
elif category == "Text":
for i, func in enumerate(buttons):
btn = Button(
self.function_frame, text=func,
command=lambda f=func: self.insert_function(f, is_text_function=True),
**{"font": (self.font_family, self.font_size), "width": 10, "height": 2}
)
btn.grid(row=row, column=i % 2, padx=5, pady=5)
row += math.ceil(len(buttons) / 2)
elif category == "Constants":
for i, func in enumerate(buttons):
btn = Button(
self.function_frame, text=func,
command=lambda f=func: self.insert_function(f, is_constant=True),
**{"font": (self.font_family, self.font_size), "width": 10, "height": 2}
)
btn.grid(row=row, column=i % 2, padx=5, pady=5)
row += math.ceil(len(buttons) / 2)
elif category == "Settings":
mode_text = "Degrees" if self.use_degrees else "Radians"
self.mode_button = Button(
self.function_frame, text=mode_text, command=self.toggle_mode,
**{"font": (self.font_family, self.font_size), "width": 10, "height": 2}
)
self.mode_button.grid(row=row, column=0, padx=5, pady=5)
row += 1
def insert_function(self, function, is_constant=False, is_text_function=False):
"""Insert the selected function into the entry field."""
current_text = self.entry_var.get()
cursor_position = self.entry.index("insert")
if is_constant:
new_text = f"{current_text[:cursor_position]}{function} "
new_cursor_position = cursor_position + len(function) + 1
elif is_text_function and function in self.text_functions:
new_text = f'{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}'
new_cursor_position = cursor_position + len(function) + 1
else:
new_text = f"{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}"
new_cursor_position = cursor_position + len(function) + 1
self.entry_var.set(new_text)
self.entry.icursor(new_cursor_position)
self.entry.focus_set()
def calculate(self):
"""Evaluate the expression entered by the user."""
expression = self.entry_var.get().strip()
if expression and expression != 'Enter Expression':
result = evaluate_expression(expression, self.variables, use_degrees=self.use_degrees)
self.display_result(expression, result)
self.entry_var.set('')
def display_result(self, expression, result):
"""Display the result in the history."""
mode = "D" if self.use_degrees else "R"
if re.match(r'^\s*[a-zA-Z_]\w*\s*=\s*.+$', expression):
history_entry = f"[{mode}] {result}\n"
else:
history_entry = f"[{mode}] {expression} = {result}\n"
self.history_entries.append(history_entry)
self.refresh_history()
self.history_text.see(END)
def toggle_search(self):
"""Toggle the visibility of the search bar."""
if self.search_bar.winfo_ismapped():
self.search_bar.place_forget()
else:
self.search_bar.place(x=150, y=0, width=300, height=24)
self.search_bar.focus_set()
def filter_history(self):
"""Filter the history based on search text."""
filter_text = self.search_var.get().lower()
self.refresh_history(filter_text)
def refresh_history(self, filter_text=""):
"""Refresh the history display, optionally filtering results."""
self.history_text.config(state='normal')
self.history_text.delete(1.0, END)
for entry in self.history_entries:
if filter_text in entry.lower():
self.history_text.insert(END, entry)
self.history_text.config(state='disabled')
def toggle_mode(self):
"""Toggle between degrees and radians for trigonometric functions."""
self.use_degrees = not self.use_degrees
self.mode_button.config(text="Degrees" if self.use_degrees else "Radians")
def toggle_vars_overlay(self):
"""Toggle the visibility of the variables overlay."""
if self.vars_overlay.winfo_ismapped():
self.vars_overlay.place_forget()
self.vars_delete_button.place_forget()
else:
self.update_vars_overlay()
self.vars_overlay.place(x=460, y=0, width=300, height=24)
self.vars_delete_button.place(x=760, y=4, width=16, height=16)
def update_vars_overlay(self):
"""Update the text displayed in the variables overlay."""
if not self.variables:
self.vars_overlay.config(state='normal')
self.vars_overlay.delete(0, END)
self.vars_overlay.insert(0, "No variables assigned.")
self.vars_overlay.config(state='readonly')
else:
vars_text = ", ".join(f"{var} = {value}" for var, value in self.variables.items())
self.vars_overlay.config(state='normal')
self.vars_overlay.delete(0, END)
self.vars_overlay.insert(0, vars_text)
self.vars_overlay.config(state='readonly')
def clear_history(self):
"""Clear the calculation history."""
self.history_entries.clear()
self.refresh_history()
def clear_variables(self):
"""Clear all assigned variables."""
self.variables.clear()
self.update_vars_overlay()
def save_data(self):
"""Save history and variables to a file."""
try:
data = {
'history': self.history_entries,
'variables': self.variables
}
file_path = filedialog.asksaveasfilename(
defaultextension=".json",
filetypes=[("JSON Files", "*.json"), ("All Files", "*.*")]
)
if file_path:
with open(file_path, 'w') as f:
json.dump(data, f, indent=4)
messagebox.showinfo("Save Successful", f"Data saved to {file_path}")
except Exception as e:
messagebox.showerror("Save Failed", f"An error occurred while saving: {e}")
def load_data(self):
"""Load history and variables from a file."""
try:
file_path = filedialog.askopenfilename(
filetypes=[("JSON Files", "*.json"), ("All Files", "*.*")]
)
if file_path:
with open(file_path, 'r') as f:
data = json.load(f)
if 'history' in data and 'variables' in data:
self.history_entries = data['history']
self.variables = data['variables']
self.refresh_history()
self.update_vars_overlay()
messagebox.showinfo("Load Successful", f"Data loaded from {file_path}")
else:
messagebox.showwarning("Invalid Data", "The selected file does not contain valid calculator data.")
except Exception as e:
messagebox.showerror("Load Failed", f"An error occurred while loading: {e}")
def load_saved_data(self):
"""Load history and variables from a default save file if it exists."""
default_save = self.script_dir / 'calculator_save.json'
if default_save.exists():
try:
with default_save.open('r') as f:
data = json.load(f)
self.history_entries = data.get('history', [])
self.variables = data.get('variables', {})
self.refresh_history()
self.update_vars_overlay()
except Exception as e:
messagebox.showwarning("Load Failed", f"Failed to load saved data: {e}")
def on_close(self):
"""Save data before closing the application."""
try:
data = {
'history': self.history_entries,
'variables': self.variables
}
default_save = self.script_dir / 'calculator_save.json'
with default_save.open('w') as f:
json.dump(data, f, indent=4)
except Exception as e:
messagebox.showwarning("Auto-Save Failed", f"Failed to auto-save data: {e}")
self.root.destroy()
def main():
"""Main function to run the calculator application."""
root = Tk()
app = CalculatorGUI(root)
root.protocol("WM_DELETE_WINDOW", app.on_close)
root.mainloop()
if __name__ == "__main__":
main()
Key Changes and Implementations:
-
Tkinter Imports: Replaced all PySide6 imports with Tkinter equivalents.
-
LongPressButton: Implemented a custom LongPressButton using threading to handle long-press actions.
-
Widgets Replacement:
QLineEdit ➔ Entry
QTextEdit ➔ Text
QPushButton ➔ Button
QScrollBar ➔ Scrollbar
QMessageBox ➔ messagebox from Tkinter
- Layouts are managed using
pack, grid, and place where appropriate.
-
Event Handling: Utilized Tkinter's event bindings (<Return>, <KeyRelease>, etc.) to handle user interactions.
-
Styling: Basic styling is applied using Tkinter's options. For more advanced styling, additional libraries like ttk or tkinter.ttk.Style can be used.
-
Data Persistence: The application saves and loads data using JSON files, similar to the original PySide6 implementation.
-
Overlay Elements: The search bar and variables overlay are managed using the place geometry manager and toggled with visibility settings.
-
Function Buttons Layout: Buttons are organized into categories using Tkinter’s grid system within frames for better structure and responsiveness.
Notes:
-
Threading in LongPressButton: Tkinter is not thread-safe, but for simple callbacks triggered by a timer, this implementation should work. However, for more complex interactions, consider using the after method from Tkinter to handle timing without threading.
-
Responsive Design: Tkinter’s grid and pack managers are used to create a responsive layout. Adjustments might be necessary based on specific requirements.
-
Error Handling: Similar error handling is maintained using messagebox to inform users of any issues during save/load operations.
-
Fonts and Styling: Adjust the font_family and font_size variables as needed to match the desired appearance.
Feel free to further customize the GUI components, styles, and functionalities to better fit your specific needs!