import tkinter as tk
from tkinter import ttk, messagebox

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

        # 模拟汇率：1单位外币兑换人民币
        self.rate = {
            "人民币(CNY)": 1.0,
            "美元(USD)": 7.22,
            "欧元(EUR)": 7.85,
            "英镑(GBP)": 9.15,
            "日元(JPY)": 0.047
        }
        currency_list = list(self.rate.keys())

        # 输入金额
        ttk.Label(root, text="输入金额：", font=("SimHei",11)).place(x=30, y=30)
        self.var_amount = tk.StringVar()
        entry_amount = ttk.Entry(root, textvariable=self.var_amount, font=("SimHei",12))
        entry_amount.place(x=130, y=30, width=220)

        # 源货币
        ttk.Label(root, text="原始货币：", font=("SimHei",11)).place(x=30, y=80)
        self.var_from = tk.StringVar()
        cbb_from = ttk.Combobox(root, textvariable=self.var_from, values=currency_list, state="readonly", font=("SimHei",11))
        cbb_from.current(0)
        cbb_from.place(x=130, y=80, width=220)

        # 目标货币
        ttk.Label(root, text="转换为：", font=("SimHei",11)).place(x=30, y=130)
        self.var_to = tk.StringVar()
        cbb_to = ttk.Combobox(root, textvariable=self.var_to, values=currency_list, state="readonly", font=("SimHei",11))
        cbb_to.current(1)
        cbb_to.place(x=130, y=130, width=220)

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

        # 输出结果
        self.result_text = tk.StringVar()
        ttk.Label(root, textvariable=self.result_text, font=("SimHei",12,"bold"), foreground="#d02020").place(x=40, y=230)

    def do_convert(self):
        """执行货币转换逻辑"""
        amount_str = self.var_amount.get().strip()
        from_cur = self.var_from.get()
        to_cur = self.var_to.get()

        # 校验输入数字
        try:
            amount = float(amount_str)
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数字金额！")
            self.result_text.set("")
            return

        if amount < 0:
            messagebox.showwarning("提示", "金额不能为负数")
            return

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

        self.result_text.set(f"转换结果：{target_value:.2f} {to_cur}")


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