-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
460 lines (374 loc) · 14.7 KB
/
Copy pathgui.py
File metadata and controls
460 lines (374 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
"""Interfaz gráfica de usuario (GUI) para la calculadora.
Este módulo implementa una calculadora con interfaz tkinter que incluye:
- Operaciones básicas: suma, resta, multiplicación, división, potencia
- Funciones científicas: valor absoluto, máximo, mínimo
- Soporte para teclado y números negativos
- Manejo de errores con mensajes visuales
"""
import tkinter as tk
try:
from .calculator import add, subtract, multiply, divide, power, valor_maximo, valor_minimo, abs_value
except ImportError:
from calculator import add, subtract, multiply, divide, power, valor_maximo, valor_minimo, abs_value
class CalculatorGUI:
def __init__(self, root):
self.root = root
self.root.title("Calculadora")
self.root.geometry("330x450")
self.root.configure(bg="#1E1E1E")
# Estado
self.current_value = ""
self.operator = None
self.first_number = None
# Interfaz de usuario
self.create_widgets()
# Activar captura de teclado
self.root.bind('<Key>', self.handle_keypress)
def create_widgets(self):
COLORS = {
"bg": "#1E1E1E",
"display": "#2B2B2B",
"numbers": "#3A3A3A",
"operators": "#FF8C00",
"equal": "#FF8C00",
"clear": "#6E6E6E",
"text": "#FFFFFF",
"error": "#FF4444"
}
# Display principal
self.display = tk.Entry(
self.root,
font=("Arial", 28, "bold"),
justify="right",
bg=COLORS["display"],
fg=COLORS["text"],
relief="flat",
bd=10
)
self.display.grid(row=0, column=0, columnspan=4, sticky="nsew", padx=10, pady=(10, 0))
# Label para mensajes de error
self.error_label = tk.Label(
self.root,
text="",
font=("Arial", 12),
bg=COLORS["bg"],
fg=COLORS["error"],
height=1
)
self.error_label.grid(row=1, column=0, columnspan=4, sticky="ew", padx=10, pady=(0, 5))
# Definición de botones
buttons = [
('C', 2, 0, COLORS["clear"]),
('(', 2, 1, COLORS["numbers"]),
(')', 2, 2, COLORS["numbers"]),
('⌫', 2, 3, COLORS["clear"]),
('max', 3, 0, COLORS["numbers"]),
('min', 3, 1, COLORS["numbers"]),
('abs', 3, 2, COLORS["numbers"]),
('/', 3, 3, COLORS["operators"]),
('7', 4, 0, COLORS["numbers"]),
('8', 4, 1, COLORS["numbers"]),
('9', 4, 2, COLORS["numbers"]),
('*', 4, 3, COLORS["operators"]),
('4', 5, 0, COLORS["numbers"]),
('5', 5, 1, COLORS["numbers"]),
('6', 5, 2, COLORS["numbers"]),
('-', 5, 3, COLORS["operators"]),
('1', 6, 0, COLORS["numbers"]),
('2', 6, 1, COLORS["numbers"]),
('3', 6, 2, COLORS["numbers"]),
('+', 6, 3, COLORS["operators"]),
('^', 7, 0, COLORS["operators"]),
('0', 7, 1, COLORS["numbers"]),
('.', 7, 2, COLORS["numbers"]),
('=', 7, 3, COLORS["equal"]),
]
# Asignar función a cada botón
for (txt, r, c, color) in buttons:
if txt.isdigit():
cmd = lambda t=txt: self.number_button_click(t)
elif txt == '.':
cmd = self.decimal_click
elif txt in ['+', '-', '*', '/', '^']:
cmd = lambda t=txt: self.operation_click(t)
elif txt == '=':
cmd = self.equals_click
elif txt == 'C':
cmd = self.clear_click
elif txt == '⌫':
cmd = self.backspace_click
elif txt in ['abs', 'max', 'min']:
cmd = lambda t=txt: self.scientific_click(t)
else:
cmd = lambda: None
tk.Button(
self.root,
text=txt,
bg=color,
fg=COLORS["text"],
font=("Arial", 16, "bold"),
relief="flat",
bd=0,
activebackground=color,
activeforeground=COLORS["text"],
highlightthickness=0,
command=cmd
).grid(row=r, column=c, padx=4, pady=4, sticky="nsew")
# Hacer que los botones se expandan con la ventana
for i in range(8):
self.root.grid_rowconfigure(i, weight=1)
for i in range(4):
self.root.grid_columnconfigure(i, weight=1)
def handle_keypress(self, event):
"""Maneja las teclas presionadas por el usuario.
Mapea las teclas del teclado a las funciones de la calculadora.
"""
key = event.char
# Dígitos 0-9
if key.isdigit():
self.number_button_click(key)
# Operadores básicos
elif key in ['+', '-', '*', '/']:
self.operation_click(key)
# Potencia
elif key == '^':
self.operation_click('^')
# Decimal
elif key == '.':
self.decimal_click()
# Calcular (Enter o =)
elif key in ['\r', '\n', '=']:
self.equals_click()
# Limpiar todo (Escape)
elif event.keysym == 'Escape':
self.clear_click()
# Borrar último carácter (Backspace)
elif event.keysym == 'BackSpace':
self.backspace_click()
def number_button_click(self, valor):
"""Maneja clicks de botones numéricos.
Args:
value (str): Dígito presionado (0-9)
Examples:
>>> # Usuario presiona 2, 3, 5
>>> # Display muestra: "235"
"""
# Validar que sea un dígito
if not str(valor).isdigit():
self.show_error("Número inválido")
return
self.current_value += str(valor)
self.display.delete(0, tk.END)
self.display.insert(0, self.current_value)
def decimal_click(self):
"""Maneja click del botón decimal con validaciones mejoradas.
Corrige casos como:
"-" + "." → "-0."
"-.3" → "-0.3"
Previene:
"-." como número inválido.
"""
# --- Caso 1: si el usuario presiona "." justo después de "-" ---
if self.current_value == "-":
# Autocompletar a -0.
self.current_value = "-0."
self.display.delete(0, tk.END)
self.display.insert(0, self.current_value)
return
# --- Caso 2: si no hay nada escrito, iniciar con "0." ---
if not self.current_value:
self.current_value = "0."
self.display.delete(0, tk.END)
self.display.insert(0, self.current_value)
return
# --- Caso 3: evitar doble punto ---
if '.' in self.current_value:
return
# --- Caso 4: validar número antes de agregar punto ---
try:
# Permitir cadenas como "5", "-3", "12"
float(self.current_value)
except ValueError:
self.show_error("Número inválido")
return
# --- Agregar el punto decimal ---
self.current_value += '.'
self.display.delete(0, tk.END)
self.display.insert(0, self.current_value)
def operation_click(self, operation):
"""Maneja clicks de operadores matemáticos.
Guarda el primer número y operador para calcular cuando
el usuario presione "=".
Args:
operation (str): Operador (+, -, *, /, ^, max, min)
Examples:
>>> # Usuario: 5 + 3 =
>>> # 1. Ingresa "5"
>>> # 2. Click "+": first_number=5, operator="+"
>>> # 3. Ingresa "3"
>>> # 4. Click "=": calcula 5+3=8
"""
# Permitir números negativos si se presiona '-' al inicio
if operation == '-' and (self.current_value == "" or self.current_value is None):
self.current_value = '-'
self.display.delete(0, tk.END)
self.display.insert(0, self.current_value)
return
if operation == '-' and self.current_value == '-':
return
# Cambiar de operador si ya hay uno seleccionado
if not self.current_value:
if self.first_number is not None:
self.operator = operation
return
# Validar que sea un número válido
try:
value = float(self.current_value)
except ValueError:
self.show_error("Número inválido")
return
# Guardar primer número
if self.first_number is None:
self.first_number = value
self.operator = operation
self.current_value = ""
return
# Calcular operación pendiente antes de la nueva
if self.first_number is not None and self.operator is not None:
self.equals_click()
try:
self.first_number = float(self.current_value)
except ValueError:
self.show_error("Número inválido")
return
self.operator = operation
self.current_value = ""
def equals_click(self):
"""Calcula el resultado de la operación actual.
Usa las funciones de calculator. py para realizar el cálculo.
Examples:
>>> # Usuario: 5 + 3 =
>>> # first_number=5, operator="+", current_value="3"
>>> # Ejecuta: add(5, 3) = 8
>>> # Display: "8"
"""
if self.first_number is not None and self.operator is not None and not self.current_value:
self.show_error("Ingresa el segundo número")
return
elif self.first_number is not None and self.operator is not None and self.current_value:
try:
second_number = float(self.current_value)
result = None
if self.operator == '+':
result = add(self.first_number, second_number)
elif self.operator == '-':
result = subtract(self.first_number, second_number)
elif self.operator == '*':
result = multiply(self.first_number, second_number)
elif self.operator == '/':
result = divide(self.first_number, second_number)
elif self.operator == '^':
result = power(self.first_number, second_number)
elif self.operator == 'max':
result = valor_maximo(self.first_number, second_number)
elif self.operator == 'min':
result = valor_minimo(self.first_number, second_number)
self.display.delete(0, tk.END)
self.display.insert(0, str(result))
self.current_value = str(result)
self.first_number = None
self.operator = None
except ValueError:
self.show_error("Entrada inválida")
return
except ZeroDivisionError:
self.show_error("No se puede dividir por 0")
return
except Exception as e:
self.show_error(str(e))
return
def clear_click(self):
"""Limpia completamente el display y resetea el estado de la calculadora.
Resetea:
- current_value: cadena vacía
- operator: None
- first_number: None
- Display: vacío
Examples:
>>> # Display muestra: "235"
>>> # Usuario presiona C
>>> # Display muestra: ""
"""
self.current_value = ""
self.operator = None
self.first_number = None
self.display.delete(0, tk.END)
self.error_label.config(text="") # Limpiar también el error
def backspace_click(self):
"""Elimina el último carácter del display.
Si el display está vacío, no hace nada.
Examples:
>>> # Display muestra: "1234"
>>> # Usuario presiona ⌫
>>> # Display muestra: "123"
>>> # Usuario presiona ⌫ tres veces más
>>> # Display muestra: ""
"""
if self.current_value:
self.current_value = self.current_value[:-1]
self.display.delete(0, tk.END)
self.display.insert(0, self.current_value)
def show_error(self, message):
"""Muestra un mensaje de error en el label de errores.
Args:
message (str): Mensaje de error a mostrar
Examples:
>>> self.show_error("División por 0")
>>> # Label de error: "⚠️ División por 0"
"""
self.error_label.config(text=f"⚠️ {message}")
# Limpiar error después de 3 segundos
self.root.after(3000, lambda: self.error_label.config(text=""))
# Resetear estado
self.current_value = ""
self.first_number = None
self.operator = None
# Limpiar el display también
self.display.delete(0, tk.END)
def unary_operation(self, func):
if self.current_value:
if self.current_value == "-":
self.show_error("Número incompleto")
return
try:
result = None
if func == 'abs':
result = abs_value(float(self.current_value))
#elif func == 'cos':
self.display.delete(0, tk.END)
self.display.insert(0, str(result))
self.current_value = str(result)
self.first_number = None
self.operator = None
except Exception as e:
self.show_error(str(e))
def scientific_click(self, func):
"""Maneja clicks de funciones científicas.
Args:
func (str): Función científica (abs, max, min)
Examples:
>>> # abs: Display "-5" → click "abs" → "5"
>>> # max: "10" → "max" → "20" → "=" → "20"
"""
# Funciones que solo necesitan un número
if func in ['abs', 'cos', 'sin', 'tan']:
self.unary_operation(func)
# Funciones que necesitan dos números
elif func in ['max', 'min']:
self.operation_click(func)
def main():
root = tk.Tk()
app = CalculatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()