Загрузка данных


from tkinter import *
from tkinter import ttk
import datetime

# Главное окно
root = Tk()
root.title("Конвертер Единиц - Контрольная")
root.geometry("500x400")
root.resizable(False, False)

# Переменные
value = DoubleVar()
result = StringVar()
history = []

# ===================== ФУНКЦИИ =====================

def convert():
    try:
        num = value.get()
        conv_type = combo_type.get()
        
        if conv_type == "Температура":
            from_unit = combo_from.get()
            to_unit = combo_to.get()
            
            if from_unit == "Цельсий" and to_unit == "Фаренгейт":
                res = num * 9/5 + 32
            elif from_unit == "Фаренгейт" and to_unit == "Цельсий":
                res = (num - 32) * 5/9
            elif from_unit == "Цельсий" and to_unit == "Кельвин":
                res = num + 273.15
            elif from_unit == "Кельвин" and to_unit == "Цельсий":
                res = num - 273.15
            else:
                res = num  # если одинаковые
                
            result.set(f"{res:.4f} {to_unit}")
            
        # Можно добавить другие типы позже
        
        # Сохраняем в историю
        time_now = datetime.datetime.now().strftime("%H:%M:%S")
        history.append(f"[{time_now}] {num} {from_unit} → {res:.4f} {to_unit}")
        
        update_history()
        
    except:
        result.set("Ошибка! Введите число")


def update_history():
    listbox.delete(0, END)
    for item in history[-8:]:   # показываем последние 8
        listbox.insert(END, item)


def change_type(*args):
    """Меняет доступные единицы измерения в зависимости от типа"""
    t = combo_type.get()
    
    combo_from['values'] = ()
    combo_to['values'] = ()
    
    if t == "Температура":
        units = ["Цельсий", "Фаренгейт", "Кельвин"]
    elif t == "Длина":
        units = ["Метры", "Километры", "Сантиметры", "Миллиметры"]
    else:
        units = ["Единица1", "Единица2"]
    
    combo_from['values'] = units
    combo_to['values'] = units
    combo_from.current(0)
    combo_to.current(1)


# ===================== ИНТЕРФЕЙС =====================

Label(root, text="Конвертер Единиц", font=("Arial", 16, "bold")).pack(pady=10)

# Выбор типа конвертера
Label(root, text="Тип конвертера:").pack(anchor=W, padx=20)
combo_type = ttk.Combobox(root, values=["Температура", "Длина"], state="readonly")
combo_type.current(0)
combo_type.pack(padx=20, fill=X)
combo_type.bind("<<ComboboxSelected>>", change_type)

# Ввод значения
frame = Frame(root)
frame.pack(pady=10, padx=20, fill=X)

Label(frame, text="Значение:").pack(side=LEFT)
Entry(frame, textvariable=value, width=15, font=("Arial", 12)).pack(side=LEFT, padx=10)

# Из каких единиц
Label(root, text="Из:").pack(anchor=W, padx=20)
combo_from = ttk.Combobox(root, state="readonly")
combo_from.pack(padx=20, fill=X)

# В какие единицы
Label(root, text="В:").pack(anchor=W, padx=20)
combo_to = ttk.Combobox(root, state="readonly")
combo_to.pack(padx=20, fill=X)

# Кнопка
Button(root, text="Конвертировать", font=("Arial", 12), bg="#4CAF50", fg="white", command=convert).pack(pady=15)

# Результат
Label(root, text="Результат:", font=("Arial", 11)).pack(anchor=W, padx=20)
Label(root, textvariable=result, font=("Arial", 14, "bold"), fg="blue").pack(pady=5)

# История
Label(root, text="История конверсий:", font=("Arial", 11)).pack(anchor=W, padx=20)
listbox = Listbox(root, height=8)
listbox.pack(padx=20, pady=5, fill=BOTH, expand=True)

# Запуск начальных единиц
change_type()

root.mainloop()