每天一個(gè)python小程序1,天氣預(yù)報(bào)
# 導(dǎo)入所需庫
import tkinter as tk
from tkinter import ttk
from ttkthemes import ThemedTk
import requests
from pypinyin import lazy_pinyin
import datetime
# API 信息
API_KEY = "a099e91c70f67ce0764cee842694fd"
CURRENT_WEATHER_URL = "https://api.openweathermap.org/data/2.5/weather"
FORECAST_WEATHER_URL = "https://api.openweathermap.org/data/2.5/forecast"
# 獲取當(dāng)前天氣信息
def get_weather(city_name):
? ?url = f"{CURRENT_WEATHER_URL}?q={city_name}&appid={API_KEY}&units=metric&lang=zh_cn"
response = requests.get(url)
? ?return response.json()
# 獲取未來五天天氣預(yù)報(bào)信息
def get_weather_forecast(city_name):
? ?url = f"{FORECAST_WEATHER_URL}?q={city_name}&appid={API_KEY}&units=metric&lang=zh_cn&cnt=40"
response = requests.get(url)
? ?return response.json()
# 查詢天氣信息并顯示在界面上
def fetch_weather(event=None):
? ?city_name = city_entry.get()
? ?if not city_name:
? ? ? ?result.set("請輸入城市名稱。")
? ? ? ?return
? ?if city_name[0] >= u'\u4e00' and city_name[-1] <= u'\u9fff':
? ? ? ?city_name = ''.join(lazy_pinyin(city_name))
? ?weather_data = get_weather(city_name)
? ?weather_forecast_data = get_weather_forecast(city_name)
? ?if weather_data.get("cod") != 200 or weather_forecast_data.get("cod") != "200":
? ? ? ?result.set("無法獲取天氣信息,請檢查輸入的城市名稱。")
? ?else:
? ? ? ?weather = weather_data["weather"][0]["description"]
? ? ? ?temp = weather_data["main"]["temp"]
? ? ? ?humidity = weather_data["main"]["humidity"]
? ? ? ?wind_speed = weather_data["wind"]["speed"]
? ? ? ?forecast = "\n未來五天天氣預(yù)報(bào):\n"
for i, forecast_data in enumerate(weather_forecast_data["list"]):
? ? ? ? ? ?if i % 8 == 0:
? ? ? ? ? ? ? ?forecast_date = datetime.datetime.strptime(forecast_data["dt_txt"], '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d')
? ? ? ? ? ? ? ?forecast_temp_min = forecast_data["main"]["temp_min"]
? ? ? ? ? ? ? ?forecast_temp_max = forecast_data["main"]["temp_max"]
? ? ? ? ? ? ? ?forecast_weather = forecast_data["weather"][0]["description"]
? ? ? ? ? ? ? ?forecast += f"{forecast_date}: 溫度 {forecast_temp_min} ~ {forecast_temp_max}°C, 天氣 {forecast_weather}\n"
result.set(f"當(dāng)前天氣:{weather}\n溫度:{temp}°C\n濕度:{humidity}%\n風(fēng)速:{wind_speed} 米/秒{forecast}")
# 創(chuàng)建主窗口
root = ThemedTk(theme="arc")
root.title("天氣預(yù)報(bào)")
# 設(shè)置窗口大小
root.geometry("450x400")
# 讓窗口居中
window_width = root.winfo_reqwidth()
window_height = root.winfo_reqheight()
position_right = int(root.winfo_screenwidth() / 2 - window_width / 2)
position_down = int(root.winfo_screenheight() / 2 - window_height / 2)
root.geometry("+{}+{}".format(position_right, position_down))
# 創(chuàng)建輸入框標(biāo)簽
city_label = ttk.Label(root, text="請輸入城市名稱(拼音/漢字):")
city_label.pack(pady=10)
# 創(chuàng)建城市輸入框
city_entry = ttk.Entry(root)
city_entry.pack(pady=5)
# 創(chuàng)建查詢按鈕
submit_button = ttk.Button(root, text="查詢", command=fetch_weather)
submit_button.pack(pady=10)
# 創(chuàng)建結(jié)果顯示標(biāo)簽
result = tk.StringVar()
result_label = ttk.Label(root, textvariable=result, wraplength=400)
result_label.pack(pady=10)
# 綁定回車鍵事件,使用戶可以按回車鍵查詢天氣
city_entry.bind("<Return>", fetch_weather)
# 運(yùn)行主程序循環(huán)
root.mainloop()