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


from tkinter import *
from tkinter import ttk
import datetime

# Главное окно
root = Tk()
root.title("Unit Converter")
root.geometry("500x450")
root.resizable(False, False)

# Переменные
val = DoubleVar()        # введённое число
res = StringVar()        # результат
history = []             # история конверсий


# ===================== ОСНОВНАЯ ФУНКЦИЯ =====================
def convert():
    try:
        num = val.get()
        conv_type = combo_type.get()
        from_unit = combo_from.get()
        to_unit = combo_to.get()
        
        answer = num   # по умолчанию

        # Температура
        if conv_type == "Temperature":
            if from_unit == "Celsius" and to_unit == "Fahrenheit":
                answer = num * 9/5 + 32
            elif from_unit == "Fahrenheit" and to_unit == "Celsius":
                answer = (num - 32) * 5/9
            elif from_unit == "Celsius" and to_unit == "Kelvin":
                answer = num + 273.15
            elif from_unit == "Kelvin" and to_unit == "Celsius":
                answer = num - 273.15

        # Длина
        elif conv_type == "Length":
            if from_unit == "Meters" and to_unit == "Kilometers":
                answer = num / 1000
            elif from_unit == "Kilometers" and to_unit == "Meters":
                answer = num * 1000
            elif from_unit == "Meters" and to_unit == "Centimeters":
                answer = num * 100
            elif from_unit == "Centimeters" and to_unit == "Meters":
                answer = num / 100

        # Показываем результат
        res.set(f"{answer:.4f} {to_unit}")

        # Сохраняем в историю
        time_now = datetime.datetime.now().strftime("%H:%M")
        history.append(f"[{time_now}] {num} {from_unit} → {answer:.4f} {to_unit}")
        
        update_history()

    except:
        res.set("Error! Enter a number")


def update_history():
    listbox.delete(0, END)
    for item in history[-7:]:
        listbox.insert(END, item)


def change_type(*args):
    conv_type = combo_type.get()
    
    if conv_type == "Temperature":
        units = ["Celsius", "Fahrenheit", "Kelvin"]
    else:  # Length
        units = ["Meters", "Kilometers", "Centimeters"]
    
    combo_from['values'] = units
    combo_to['values'] = units
    combo_from.current(0)
    combo_to.current(1)


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

Label(root, text="Unit Converter", font=("Arial", 16, "bold")).pack(pady=10)

# Тип конвертера
Label(root, text="Type:").pack(anchor=W, padx=20)
combo_type = ttk.Combobox(root, values=["Temperature", "Length"], 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="Value:").pack(side=LEFT)
Entry(frame, textvariable=val, width=15, font=("Arial", 12)).pack(side=LEFT, padx=10)

# Из
Label(root, text="From:").pack(anchor=W, padx=20)
combo_from = ttk.Combobox(root, state="readonly")
combo_from.pack(padx=20, fill=X)

# В
Label(root, text="To:").pack(anchor=W, padx=20)
combo_to = ttk.Combobox(root, state="readonly")
combo_to.pack(padx=20, fill=X)

# Кнопка
Button(root, text="Convert", font=("Arial", 12, "bold"), 
       bg="#4CAF50", fg="white", height=2, command=convert).pack(pady=15)

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

# История
Label(root, text="History:", 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()