Python實現(xiàn)獲取近期天氣數(shù)據(jù)并顯示在窗口
借助AI實現(xiàn)獲取指定地區(qū)的天氣的代碼,現(xiàn)在以上海天氣舉例,代碼原理是獲取指定網址網頁的天氣數(shù)據(jù),在窗口中顯示。
效果圖:

代碼演示:
import tkinter as tk
from tkinter import ttk
import requests
import json
from datetime import datetime
def get_weather(city="Shanghai"):
"""獲取天氣數(shù)據(jù)Shanghai Beijing"""
url = f"https://wttr.in/{city}?format=j1&lang=zh"
try:
resp = requests.get(url, timeout=10)
data = resp.json()
current = data['current_condition'][0]
weather_info = {
"城市": city,
"溫度": f"{current['temp_C']}°C",
"體感": f"{current['FeelsLikeC']}°C",
"天氣": current['lang_zh'][0]['value'],
"濕度": f"{current['humidity']}%",
"風速": f"{current['windspeedKmph']} km/h",
"更新時間": datetime.now().strftime("%H:%M:%S")
}
return weather_info
except Exception as e:
return {"錯誤": str(e)}
def create_window():
root = tk.Tk()
root.title("實時天氣")
root.geometry("400x350")
root.resizable(False, False)
# 標題
title_label = tk.Label(root, text="?? 天氣信息", font=("微軟雅黑", 18, "bold"))
title_label.pack(pady=15)
# 天氣數(shù)據(jù)容器
info_frame = tk.Frame(root)
info_frame.pack(pady=10, padx=20, fill="both", expand=True)
weather = get_weather()
# 逐行顯示
for i, (key, value) in enumerate(weather.items()):
frame = tk.Frame(info_frame)
frame.pack(fill="x", pady=5)
label = tk.Label(frame, text=f"{key}:", font=("微軟雅黑", 11), width=8, anchor="w")
label.pack(side="left")
value_label = tk.Label(frame, text=str(value), font=("微軟雅黑", 11, "bold"))
value_label.pack(side="left")
# 刷新按鈕
def refresh():
for widget in info_frame.winfo_children():
widget.destroy()
weather = get_weather()
for i, (key, value) in enumerate(weather.items()):
frame = tk.Frame(info_frame)
frame.pack(fill="x", pady=5)
label = tk.Label(frame, text=f"{key}:", font=("微軟雅黑", 11), width=8, anchor="w")
label.pack(side="left")
value_label = tk.Label(frame, text=str(value), font=("微軟雅黑", 11, "bold"))
value_label.pack(side="left")
btn = tk.Button(root, text="?? 刷新", command=refresh, font=("微軟雅黑", 10))
btn.pack(pady=10)
root.mainloop()
if __name__ == "__main__":
create_window()
知識擴展:
Python 獲取天氣數(shù)據(jù)的主流方式有兩種,第一種是直接調用免費天氣 API,第二種是使用封裝好的第三方 Python 庫。如果要獲取近期數(shù)據(jù),也可以選擇開放的歷史數(shù)據(jù)集進行離線分析。最簡單的莫過于無需 API 密鑰的 Open-Meteo API,幾行代碼即可開始。
方案一:直連 API
這是最靈活的方法,你可以直接控制請求和處理數(shù)據(jù)。
1. 推薦方案:Open-Meteo (完全免費,無需 API Key)
Open-Meteo 是一個非常出色的免費開源氣象 API,它整合了 NOAA、DWD 等多個全球氣象機構的模型數(shù)據(jù)。更關鍵的是,它使用起來極其簡單,無需注冊和 API Key,非常適合快速開發(fā)。
安裝依賴:
pip install requests
示例代碼:
import requests
# 柏林的地理坐標 (緯度, 經度)
berlin_lat, berlin_lon = 52.52, 13.41
# 構建請求 URL
url = "https://api.open-meteo.com/v1/forecast"
params = {
"latitude": berlin_lat,
"longitude": berlin_lon,
"current": ["temperature_2m", "relative_humidity_2m"],
"daily": "temperature_2m_max,temperature_2m_min",
"timezone": "auto"
}
response = requests.get(url, params=params)
data = response.json() # 解析 JSON 數(shù)據(jù)
# 獲取當前溫度(攝氏度)
current_temp = data['current']['temperature_2m']
# 打印結果
print(f"Berlin Current Temperature: {current_temp}°C")提示:Open-Meteo 還提供了官方 Python 庫 openmeteo-requests,如果你需要處理大量時間序列數(shù)據(jù),這個庫使用 FlatBuffers 格式,效率更高。
2. 備選方案:OpenWeatherMap
作為市場上最主流的天氣 API 之一,OpenWeatherMap 憑借其龐大的社區(qū)和詳盡的文檔,是另一個可靠的選擇。在它的免費計劃下,你可以創(chuàng)建一個小型應用的前端雛形,并根據(jù)需求擴展。
準備工作:首先需要在 OpenWeatherMap 官網注冊賬號并獲取 API Key。
示例代碼:
import requests
API_KEY = "YOUR_API_KEY" # 替換成你的 API 密鑰
city = "London"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
response = requests.get(url)
data = response.json()
# 獲取當前溫度(攝氏度)
current_temp = data['main']['temp']
print(f"{city} Current Temperature: {current_temp}°C")3. 新手友好方案:WeatherAPI
WeatherAPI.com 也是一個不錯的選擇。它的免費計劃每月提供高達 100 萬次請求,并且文檔對初學者非常友好,并提供多種天氣數(shù)據(jù)類型,能很好地平衡開發(fā)初期的需求。使用方式與 OpenWeatherMap 類似,同樣需要注冊獲取 API Key。
方案二:使用第三方庫
如果你不想直接處理 HTTP 請求細節(jié),使用這些封裝好的庫會更方便。
1. Wetterdienst:統(tǒng)一訪問多源數(shù)據(jù)
Wetterdienst 是一個強大的 Python 庫,它提供了一個統(tǒng)一的接口來訪問官方氣象服務的數(shù)據(jù)。
安裝:
pip install wetterdienst
示例代碼 (獲取柏林某時段的氣溫):
from wetterdienst import Settings
from wetterdienst.provider.dwd.observation import DwdObservationRequest
# 創(chuàng)建一個請求,指定想要的數(shù)據(jù)集
request = DwdObservationRequest(
parameter="temperature_air_2m",
resolution="daily",
period="recent",
start_date="2023-01-01",
end_date="2023-01-10",
)
# 過濾出柏林-達勒姆站點的數(shù)據(jù)
berlin_dahlem = request.filter_by_rank(latitude=52.46, longitude=13.30, rank=1)
# 獲取數(shù)據(jù)并轉換為 DataFrame
df = berlin_dahlem.values.all().to_pandas()
print(df.head())提示:Wetterdienst 可以通過 pip 安裝,且支持 Polars 等現(xiàn)代數(shù)據(jù)處理框架。
2. python-weather:輕量級異步庫
python-weather 是一個免費的、異步的天氣 API 封裝器。它的代碼非常簡潔,適合集成到異步應用中。
安裝:
pip install python-weather
示例代碼:
import asyncio
import python_weather
async def get_weather():
async with python_weather.Client() as client:
weather = await client.get("New York")
print(f"Current temperature: {weather.current.temperature}°C")
if __name__ == "__main__":
asyncio.run(get_weather())方案三:獲取歷史天氣數(shù)據(jù)集
如果你需要進行大規(guī)模的數(shù)據(jù)分析,而不是實時查詢,可以考慮使用現(xiàn)成的歷史數(shù)據(jù)集。
Open-Meteo 同樣提供了一個強大的歷史天氣 API,可以追溯到 1940 年,并支持多種數(shù)據(jù)參數(shù)。這對于學術研究或模型訓練非常有價值。
示例代碼:
import requests
url = "https://archive-api.open-meteo.com/v1/archive"
params = {
"latitude": 40.7128,
"longitude": -74.0060,
"start_date": "2025-01-01",
"end_date": "2025-01-07",
"daily": "temperature_2m_max,temperature_2m_min",
"timezone": "America/New_York"
}
response = requests.get(url, params=params)
historical_data = response.json()
# 打印歷史數(shù)據(jù)
print(historical_data)到此這篇關于Python實現(xiàn)獲取近期天氣數(shù)據(jù)并顯示在窗口的文章就介紹到這了,更多相關Python獲取天氣數(shù)據(jù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pydev debugger: process 10341 is co
這篇文章主要介紹了pydev debugger: process 10341 is connecting無法debu的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
python檢測lvs real server狀態(tài)
這篇文章主要介紹了用python檢測lvs real server狀態(tài)的示例,大家參考使用吧2014-01-01

