import tkinter as tk
from tkinter import ttk, messagebox
import requests

# 语言映射
lang_map = {
    "中文": "zh",
    "英文": "en",
    "日语": "ja",
    "韩语": "ko",
    "法语": "fr",
    "德语": "de",
    "俄语": "ru"
}
lang_list = list(lang_map.keys())

def translate_text():
    src_text = text_input.get("1.0", tk.END).strip()
    if not src_text:
        messagebox.showwarning("提示", "请输入要翻译的文本！")
        return
    src_lang = lang_map[combo_src.get()]
    dst_lang = lang_map[combo_dst.get()]

    url = "https://api.mymemory.translated.net/get"
    params = {
        "q": src_text,
        "langpair": f"{src_lang}|{dst_lang}"
    }
    try:
        res = requests.get(url, params=params, timeout=10)
        data = res.json()
        translated = data["responseData"]["translatedText"]
        text_output.delete("1.0", tk.END)
        text_output.insert(tk.END, translated)
    except Exception as e:
        messagebox.showerror("翻译失败", f"网络或接口错误：{str(e)}")

def clear_text():
    text_input.delete("1.0", tk.END)
    text_output.delete("1.0", tk.END)

def copy_result():
    res = text_output.get("1.0", tk.END).strip()
    if res:
        root.clipboard_clear()
        root.clipboard_append(res)
        messagebox.showinfo("成功", "译文已复制到剪贴板！")

# 界面
root = tk.Tk()
root.title("简易翻译器")
root.geometry("640x440")

frame_top = ttk.Frame(root)
frame_top.pack(pady=8, fill="x", padx=10)

ttk.Label(frame_top, text="源语言：").grid(row=0, column=0)
combo_src = ttk.Combobox(frame_top, values=lang_list, width=10, state="readonly")
combo_src.grid(row=0, column=1, padx=5)
combo_src.current(0)

ttk.Label(frame_top, text="目标语言：").grid(row=0, column=2, padx=(10,0))
combo_dst = ttk.Combobox(frame_top, values=lang_list, width=10, state="readonly")
combo_dst.grid(row=0, column=3, padx=5)
combo_dst.current(1)

btn_trans = ttk.Button(frame_top, text="翻译", command=translate_text)
btn_trans.grid(row=0, column=4, padx=5)
btn_clear = ttk.Button(frame_top, text="清空", command=clear_text)
btn_clear.grid(row=0, column=5, padx=2)
btn_copy = ttk.Button(frame_top, text="复制", command=copy_result)
btn_copy.grid(row=0, column=6, padx=2)

ttk.Label(root, text="原文：").pack(anchor="w", padx=10)
text_input = tk.Text(root, height=7, wrap=tk.WORD)
text_input.pack(padx=10, fill="both", expand=True)

ttk.Label(root, text="译文：").pack(anchor="w", padx=10)
text_output = tk.Text(root, height=7, wrap=tk.WORD)
text_output.pack(padx=10, fill="both", expand=True)

root.mainloop()
