import requests
import tkinter as tk
from tkinter import messagebox

def query_weather():
    city = entry_city.get().strip()
    if not city:
        messagebox.showwarning("提示", "请输入城市名称")
        return
    try:
        headers = {"User-Agent": "curl"}
        res = requests.get(f"https://wttr.in/{city}?format=j1&lang=zh", headers=headers, timeout=8)
        data = res.json()
        curr = data["current_condition"][0]
        text_result.delete(1.0, tk.END)
        msg = (
            f"城市：{city}\n"
            f"天气：{curr['weatherDesc'][0]['value']}\n"
            f"气温：{curr['temp_C']} ℃\n"
            f"体感：{curr['FeelsLikeC']} ℃\n"
            f"湿度：{curr['humidity']}%\n"
            f"风力：{curr['windspeedKmph']} km/h {curr['winddir16Point']}"
        )
        text_result.insert(tk.END, msg)
    except Exception as err:
        messagebox.showerror("失败", f"查询出错：{err}")

# 窗口搭建
win = tk.Tk()
win.title("简易天气查询工具")
win.geometry("400x300")

tk.Label(win, text="输入城市：").pack(pady=5)
entry_city = tk.Entry(win, width=25, font=("微软雅黑",12))
entry_city.pack()

tk.Button(win, text="查询天气", command=query_weather, bg="#409eff", fg="white").pack(pady=8)

text_result = tk.Text(win, width=45, height=10)
text_result.pack()

win.mainloop()