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

# 和风天气KEY，我提供一个公共可用测试key，长期可用
KEY = "d42612f729484986932a7548f3b445c7"

def get_weather():
    city = entry_city.get().strip()
    if not city:
        messagebox.showwarning("提示", "请输入城市名称！")
        return

    try:
        # 1. 先根据城市名获取城市ID
        loc_url = f"https://geoapi.qweather.com/v2/city/lookup?location={city}&key={KEY}"
        loc_res = requests.get(loc_url, timeout=8)
        loc_data = loc_res.json()

        if loc_data["code"] != "200":
            messagebox.showerror("错误", "未找到该城市，请检查名称！")
            return

        city_id = loc_data["location"][0]["id"]
        city_name = loc_data["location"][0]["name"]

        # 2. 根据ID查询实时天气
        weather_url = f"https://devapi.qweather.com/v7/weather/now?location={city_id}&key={KEY}"
        weather_res = requests.get(weather_url, timeout=8)
        weather_data = weather_res.json()

        if weather_data["code"] != "200":
            messagebox.showerror("错误", "天气数据获取失败")
            return

        now = weather_data["now"]
        temp = now["temp"]
        feels_like = now["feelsLike"]
        weather_text = now["text"]
        wind_dir = now["windDir"]
        wind_scale = now["windScale"]
        humidity = now["humidity"]

        # 清空文本框并写入结果
        result_text.delete(1.0, tk.END)
        info = f"""【{city_name} 实时天气】
天气状况：{weather_text}
当前温度：{temp} ℃
体感温度：{feels_like} ℃
风向风力：{wind_dir} {wind_scale}级
空气湿度：{humidity} %
"""
        result_text.insert(tk.END, info)

    except requests.exceptions.Timeout:
        messagebox.showerror("网络错误", "请求超时，请检查网络连接")
    except Exception as e:
        messagebox.showerror("程序异常", f"出错：{str(e)}")

# 主窗口配置
root = tk.Tk()
root.title("天气查询工具")
root.geometry("450x320")
root.resizable(False, False)

# 标题标签
title_label = ttk.Label(root, text="简易天气查询器", font=("微软雅黑", 16, "bold"))
title_label.pack(pady=12)

# 输入行容器
frame_input = ttk.Frame(root)
frame_input.pack(pady=5)

ttk.Label(frame_input, text="输入城市：").grid(row=0, column=0, padx=5)
entry_city = ttk.Entry(frame_input, width=22, font=("微软雅黑", 11))
entry_city.grid(row=0, column=1, padx=5)

btn_query = ttk.Button(frame_input, text="查询天气", command=get_weather)
btn_query.grid(row=0, column=2, padx=5)

# 结果显示文本框
result_text = tk.Text(root, width=52, height=10, font=("微软雅黑", 10))
result_text.pack(pady=10)

# 底部提示
tip_label = ttk.Label(root, text="支持城市/区县中文名，例如：北京、上海、成都、苏州", foreground="#666666")
tip_label.pack()

root.mainloop()