import tkinter as tk #导入tkinter包
from tkinter import messagebox #引用tkinter包的messagebox方法
import requests #导入requests

# 定义一个方法,获取汇率数据
def get_exchange_rate(from_currency, to_currency):#传入原币from_currency与目标币别to_currency
    url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"#获取汇率数据的WebApi接口的Url地址
    try:#异常处理,可能出现异常的代码块
        response = requests.get(url)#请求接口
        data = response.json()#返回请求结果,数据以json格式
        if "rates" in data:
            return data["rates"].get(to_currency)#按目标币别to_currency返回汇率
        else:
            raise ValueError("Invalid currency or API error")
    except Exception as e:
	#如果Url接口地址失效或网络不通就抛出异常
        messagebox.showerror("Error", f"Unable to fetch exchange rates: {e}")
        return None

# 定义方法,执行汇率转换
def convert():
    from_currency = from_currency_var.get()#获取表单 原币选择项
    to_currency = to_currency_var.get()#获取表单 目标币选择项
    try:#异常处理,可能出现异常的代码块
        amount = float(amount_entry.get())#获取表单文本的金额
        if amount <= 0:#如果当前窗口没有输入金额
            messagebox.showerror("Invalid input", "Please enter a positive number")#弹窗:提示请输入金额
            return

        exchange_rate = get_exchange_rate(from_currency, to_currency)#调用获取汇率数据
        if exchange_rate:
            result = amount * exchange_rate #如果获取到汇率就乘以原币金额
            if amount > 0:
                NewText = str("Original Currency:")+str("[") +str(from_currency)+": "+str(amount)+"]  "+str("Converted Amount:[") +str(to_currency)+str(": ")+str(result)+str("]")
                #重新拼接输出结果
            result_label.config(text = NewText)#变量回传,显示重新拼接的输出结果
            sum_result = result + amount
            open_new_window(sum_result)#调用 打开新窗口 
        else:
            result_label.config(text="Error in conversion")
    except ValueError:#如果异常就抛出异常
        messagebox.showerror("Invalid input", "Please enter a valid amount")

# 定义方法,打开新窗口
def open_new_window(sum_result):
    # 创建新窗口
    new_window = tk.Toplevel(root)    
    # 设置新窗口的标题
    new_window.title("new_window")    
    # 在新窗口中可以添加更多的组件和功能
    label = tk.Label(new_window, text=str("this is sum result:  ") + str(sum_result)) # 显示原币金额与汇率相加结果
    label.pack()
    new_window.geometry("300x100")#窗口大小
    

# 创建主窗口
root = ()
root.title("Currency Converter")
root.geometry("400x300")

# 创建UI组件
from_currency_var = tk.StringVar(value="USD")
to_currency_var = tk.StringVar(value="EUR")

# From Currency
from_currency_label = tk.Label(root, text="From Currency:")
from_currency_label.pack(pady=5)

from_currency_menu = tk.OptionMenu(root, from_currency_var, "USD", "EUR", "GBP", "JPY", "CNY", "INR")
from_currency_menu.pack(pady=5)

# Amount
amount_label = tk.Label(root, text="Amount:")
amount_label.pack(pady=5)

amount_entry = tk.Entry(root)
amount_entry.pack(pady=5)

# To Currency
to_currency_label = tk.Label(root, text="To Currency:")
to_currency_label.pack(pady=5)

to_currency_menu = tk.OptionMenu(root, to_currency_var, "USD", "EUR", "GBP", "JPY", "CNY", "INR")
to_currency_menu.pack(pady=5)

# Convert Button
convert_button = tk.Button(root, text="Convert", command=convert)
convert_button.pack(pady=10)

# Result Label
result_label = tk.Label(root, text="")#空字符串!
result_label.pack(pady=5)

# 运行应用
root.mainloop()