import tkinter as tk
from tkinter import ttk, messagebox

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

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

        # 构建界面
        self.create_widgets()

    def create_widgets(self):
        # 输入金额
        ttk.Label(self.root, text="输入金额：", font=("微软雅黑",11)).place(x=30, y=30)
        self.amount_var = tk.StringVar()
        entry_amount = ttk.Entry(self.root, textvariable=self.amount_var, font=("微软雅黑",12), width=22)
        entry_amount.place(x=110, y=30)

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

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

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

        # 清空按钮
        btn_clear = ttk.Button(self.root, text="清空", command=self.clear_all)
        btn_clear.place(x=210, y=180, width=120)

        # 结果显示
        ttk.Label(self.root, text="转换结果：", font=("微软雅黑",11)).place(x=30, y=230)
        self.result_var = tk.StringVar(value="0.00")
        ttk.Label(self.root, textvariable=self.result_var, font=("微软雅黑",13,"bold"), foreground="#0066cc").place(x=110, y=230)

    def convert(self):
        """货币换算核心逻辑"""
        try:
            amount = float(self.amount_var.get())
            from_cur = self.from_currency.get()
            to_cur = self.to_currency.get()

            # 统一换算成人民币，再转为目标货币
            cny_value = amount * self.rate[from_cur]
            target_value = cny_value / self.rate[to_cur]
            self.result_var.set(f"{target_value:.2f}")
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的数字金额！")
        except Exception as e:
            messagebox.showerror("错误", str(e))

    def clear_all(self):
        """清空输入与结果"""
        self.amount_var.set("")
        self.result_var.set("0.00")
        self.from_currency.current(0)
        self.to_currency.current(1)

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