import tkinter as tk
from tkinter import ttk, messagebox

# 模拟汇率：1单位外币兑换人民币，可自行更新汇率
exchange_rate = {
    "人民币(CNY)": 1.0,
    "美元(USD)": 7.22,
    "欧元(EUR)": 7.85,
    "英镑(GBP)": 9.12,
    "日元(JPY)": 0.047,
    "韩元(KRW)": 0.0052,
    "港币(HKD)": 0.92
}

class CurrencyConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("货币单位转换器")
        self.root.geometry("420x280")
        self.root.resizable(False, False)

        # 变量
        self.amount_var = tk.StringVar()
        self.result_var = tk.StringVar()

        currency_list = list(exchange_rate.keys())

        # 布局组件
        # 输入金额
        ttk.Label(root, text="输入金额：", font=("微软雅黑", 11)).place(x=30, y=30)
        entry_amount = ttk.Entry(root, textvariable=self.amount_var, font=("微软雅黑", 12), width=20)
        entry_amount.place(x=110, y=30)

        # 源货币
        ttk.Label(root, text="原始货币：", font=("微软雅黑", 11)).place(x=30, y=80)
        self.combo_from = ttk.Combobox(root, values=currency_list, font=("微软雅黑", 10), width=18)
        self.combo_from.place(x=110, y=80)
        self.combo_from.current(0)

        # 目标货币
        ttk.Label(root, text="转换货币：", font=("微软雅黑", 11)).place(x=30, y=130)
        self.combo_to = ttk.Combobox(root, values=currency_list, font=("微软雅黑", 10), width=18)
        self.combo_to.place(x=110, y=130)
        self.combo_to.current(1)

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

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

    def convert(self):
        try:
            amount = float(self.amount_var.get())
            from_cur = self.combo_from.get()
            to_cur = self.combo_to.get()

            # 先转成人民币，再转换成目标货币
            cny_value = amount * exchange_rate[from_cur]
            target_value = cny_value / exchange_rate[to_cur]

            self.result_var.set(f"{target_value:.2f} {to_cur}")
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数字金额！")
        except Exception as e:
            messagebox.showerror("错误", str(e))

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