import tkinter as tk
from tkinter import ttk
import requests
import json
from datetime import datetime
from ttkbootstrap import Style

class WeatherApp:
def init(self, root):
self.root = root
self.root.title("天气预报 (OpenWeatherMap)")
self.root.geometry("1000x800")

使用ttkbootstrap美化界面

style = Style(theme='cosmo')

创建主框架

self.main_frame = ttk.Frame(self.root)
self.main_frame.pack(pady=20, padx=20, fill='both', expand=True)

搜索框

self.search_frame = ttk.Frame(self.main_frame)
self.search_frame.pack(fill='x', pady=10)

self.city_entry = ttk.Entry(self.search_frame, font=('微软雅黑', 12))
self.city_entry.pack(side='left', expand=True, padx=(0, 10))
self.city_entry.insert(0, "Shanghai")

self.search_button = ttk.Button(
self.search_frame,
text="查询",
command=self.get_weather,
style='primary.TButton'
)
self.search_button.pack(side='right')

当前天气信息框

self.current_weather_frame = ttk.LabelFrame(self.main_frame, text="当前天气", padding=15)
self.current_weather_frame.pack(fill='x', pady=10)

当前天气信息

self.current_info_frame = ttk.Frame(self.current_weather_frame)
self.current_info_frame.pack(fill='x', padx=20)

self.city_label = ttk.Label(self.current_info_frame, font=('微软雅黑', 20, 'bold'))
self.city_label.pack(anchor='w')

self.temp_label = ttk.Label(self.current_info_frame, font=('微软雅黑', 30))
self.temp_label.pack(anchor='w')

self.weather_label = ttk.Label(self.current_info_frame, font=('微软雅黑', 15))
self.weather_label.pack(anchor='w')

天气图标

self.weather_icon_label = ttk.Label(self.current_info_frame)
self.weather_icon_label.pack(anchor='w')

详细信息框

self.detail_frame = ttk.LabelFrame(self.main_frame, text="详细信息", padding=15)
self.detail_frame.pack(fill='x', pady=10)

创建详细信息标签

self.details = {
"体感温度": ttk.Label(self.detail_frame),
"湿度": ttk.Label(self.detail_frame),
"气压": ttk.Label(self.detail_frame),
"能见度": ttk.Label(self.detail_frame),
"风向": ttk.Label(self.detail_frame),
"风速": ttk.Label(self.detail_frame),
"云量": ttk.Label(self.detail_frame),
"日出": ttk.Label(self.detail_frame),
"日落": ttk.Label(self.detail_frame)
}

布局详细信息

row = 0
col = 0
for key, label in self.details.items():
ttk.Label(self.detail_frame, text=f"{key}😊.grid(row=row, column=col * 2, padx=5, pady=5, sticky='e')
label.grid(row=row, column=col * 2 + 1, padx=5, pady=5, sticky='w')
col += 1
if col > 2:
col = 0
row += 1

未来天气预报框

self.forecast_frame = ttk.LabelFrame(self.main_frame, text="未来天气预报", padding=15)
self.forecast_frame.pack(fill='both', expand=True, pady=10)

创建未来5天的预报框架

self.forecast_days = []
for i in range(5):
day_frame = ttk.Frame(self.forecast_frame)
day_frame.pack(side='left', expand=True, padx=10)

date_label = ttk.Label(day_frame, font=('微软雅黑', 10))
date_label.pack()

icon_label = ttk.Label(day_frame)
icon_label.pack()

temp_label = ttk.Label(day_frame, font=('微软雅黑', 12))
temp_label.pack()

weather_label = ttk.Label(day_frame, font=('微软雅黑', 10))
weather_label.pack()

self.forecast_days.append({
'date': date_label,
'icon': icon_label,
'temp': temp_label,
'weather': weather_label
})

def get_weather(self):
city = self.city_entry.get()
api_key = "YOUR_OPENWEATHERMAP_API_KEY" # 替换为你的OpenWeatherMap API密钥
units = "metric" # 使用公制单位

获取天气数据的URL

current_url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units={units}&lang=zh_cn"
forecast_url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={api_key}&units={units}&lang=zh_cn"

try:
# 获取当前天气
current_response = requests.get(current_url)
print("Current Weather API Response:", current_response.text)

if current_response.status_code != 200:
raise Exception(f"当前天气API请求失败,状态码: {current_response.status_code}")

current_data = current_response.json()

更新当前天气信息

self.city_label.config(text=f"{current_data['name']}, {current_data['sys']['country']}")
self.temp_label.config(text=f"{current_data['main']['temp']:.1f}°C")
weather_desc = current_data['weather'][0]['description']
self.weather_label.config(te