Files
Calculater_chelgu/app/src/designer.py
2025-11-10 12:38:21 +05:00

164 lines
6.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import flet as ft
from flet.core.types import OptionalControlEventCallable
import sys
import os
# Добавляем путь к модулю step_by_step_solver
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from step_by_step_solver import StepByStepSolver, Operation
right_column = ft.Column(
horizontal_alignment=ft.CrossAxisAlignment.CENTER,
expand=True,
)
alphabet="αβγδεζηθικλμνξοπρστυφχψω"
class StepByStepDisplay:
"""
Класс для отображения пошагового решения в калькуляторах
Предоставляет унифицированный интерфейс для визуализации шагов решения
"""
# Размеры текста для различных элементов
HEADER_SIZE = 16
STEP_TITLE_SIZE = 14
DESCRIPTION_SIZE = 12
VISUAL_SIZE = 12
RESULT_SIZE = 13
ERROR_SIZE = 12
MESSAGE_SIZE = 14
@staticmethod
def create_steps_container(steps_column: ft.Column, height: int = None, width: int = None, expand: bool = True) -> ft.Container:
"""
Создает контейнер для отображения шагов решения
Args:
steps_column: колонка с шагами
height: высота контейнера (опционально)
width: ширина контейнера (опционально)
expand: растягивать контейнер (по умолчанию True)
Returns:
ft.Container с настроенным стилем
"""
container_props = {
"content": steps_column,
"bgcolor": "#1A0A2A",
"padding": 10,
"border_radius": 5,
}
if expand:
container_props["expand"] = True
if height:
container_props["height"] = height
if width:
container_props["width"] = width
return ft.Container(**container_props)
@staticmethod
def show_steps(steps_column: ft.Column, solver: StepByStepSolver, num1: str, num2: str, operation: Operation):
"""
Отображает пошаговое решение в указанной колонке
Args:
steps_column: колонка для отображения шагов
solver: экземпляр StepByStepSolver для получения шагов
num1: первое число (строка)
num2: второе число (строка)
operation: операция (Operation.ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION)
"""
try:
# Получаем шаги решения
steps = solver.solve(num1, num2, operation)
# Очищаем предыдущие шаги
steps_column.controls.clear()
# Добавляем заголовок
steps_column.controls.append(
ft.Text("📝 Ход решения:", size=StepByStepDisplay.HEADER_SIZE, weight=ft.FontWeight.BOLD, color="#FFD700")
)
# Добавляем каждый шаг
for i, step in enumerate(steps, 1):
step_content = []
# Название шага
step_content.append(
ft.Text(f"Шаг {i}: {step.title}",
size=StepByStepDisplay.STEP_TITLE_SIZE, weight=ft.FontWeight.BOLD, color="#00FFFF")
)
# Описание
step_content.append(
ft.Text(step.description, size=StepByStepDisplay.DESCRIPTION_SIZE, color="#E0E0E0")
)
# Визуализация (если есть)
if step.visual:
step_content.append(
ft.Text(step.visual,
size=StepByStepDisplay.VISUAL_SIZE,
font_family="Courier New",
color="#90EE90",
selectable=True)
)
# Результат (если есть)
if step.result:
step_content.append(
ft.Text(f"{step.result}",
size=StepByStepDisplay.RESULT_SIZE,
weight=ft.FontWeight.BOLD,
color="#00FF00")
)
# Добавляем контейнер с шагом
steps_column.controls.append(
ft.Container(
content=ft.Column(step_content, spacing=3),
bgcolor="#2A1A3A",
padding=8,
border_radius=5,
border=ft.border.all(1, "#4A3A5A")
)
)
steps_column.update()
except Exception as ex:
steps_column.controls.clear()
steps_column.controls.append(
ft.Text(f"Ошибка при генерации решения: {str(ex)}", color="red", size=StepByStepDisplay.ERROR_SIZE)
)
steps_column.update()
@staticmethod
def show_message(steps_column: ft.Column, message: str, color: str = "#FFD700"):
"""
Отображает сообщение в колонке шагов (например, для дробных чисел)
Args:
steps_column: колонка для отображения
message: текст сообщения
color: цвет текста (по умолчанию золотой)
"""
steps_column.controls.clear()
steps_column.controls.append(
ft.Text(message, color=color, size=StepByStepDisplay.MESSAGE_SIZE)
)
steps_column.update()
class Obstr(ft.Column):
def __init__(self):
super().__init__(
controls=[
]
)