import tkinter as tk
from tkinter import ttk, messagebox

class LengthConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("长度单位转换器")
        self.root.geometry("460x300")
        self.root.resizable(False, False)

        # 以米(m)作为基准单位
        unit_rate = {
            "米(m)": 1,
            "千米(km)": 1000,
            "厘米(cm)": 0.01,
            "毫米(mm)": 0.001,
            "英里(mi)": 1609.34,
            "码(yd)": 0.9144,
            "英尺(ft)": 0.3048,
            "英寸(in)": 0.0254
        }
        self.unit_rate = unit_rate
        unit_list = list(unit_rate.keys())

        self.input_var = tk.StringVar()
        self.result_var = tk.StringVar()

        # 输入长度
        ttk.Label(root, text="输入数值：", font=("微软雅黑", 11)).place(x=30, y=30)
        entry_input = ttk.Entry(root, textvariable=self.input_var, font=("微软雅黑", 12), width=22)
        entry_input.place(x=110, y=30)

        # 原始单位
        ttk.Label(root, text="原始单位：", font=("微软雅黑", 11)).place(x=30, y=85)
        self.combo_from = ttk.Combobox(root, values=unit_list, font=("微软雅黑", 10), width=20)
        self.combo_from.place(x=110, y=85)
        self.combo_from.current(0)

        # 目标单位
        ttk.Label(root, text="转换单位：", font=("微软雅黑", 11)).place(x=30, y=140)
        self.combo_to = ttk.Combobox(root, values=unit_list, font=("微软雅黑", 10), width=20)
        self.combo_to.place(x=110, y=140)
        self.combo_to.current(2)

        # 转换按钮
        btn_convert = ttk.Button(root, text="开始转换", command=self.convert)
        btn_convert.place(x=160, y=195)

        # 结果显示
        ttk.Label(root, text="转换结果：", font=("微软雅黑", 11)).place(x=30, y=250)
        label_result = ttk.Label(root, textvariable=self.result_var,
                                 font=("微软雅黑", 12, "bold"), foreground="#c82423")
        label_result.place(x=110, y=250)

    def convert(self):
        try:
            num = float(self.input_var.get())
            u_from = self.combo_from.get()
            u_to = self.combo_to.get()

            # 先统一换算成米，再转为目标单位
            meter = num * self.unit_rate[u_from]
            output = meter / self.unit_rate[u_to]
            self.result_var.set(f"{output:.4f} {u_to}")
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数字！")

if __name__ == "__main__":
    window = tk.Tk()
    app = LengthConverter(window)
    window.mainloop()