用Python写一个天气预报小程序

devtools/2025/3/13 17:41:33/

一、界面效果

二、完整代码

import tkinter as tk
from tkinter import ttk
import requests
import json
from datetime import datetime
from PIL import Image, ImageTk
import io
from ttkbootstrap import Styleclass WeatherApp:def __init__(self, root):self.root = rootself.root.title("天气预报")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, "上海")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.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)}# 布局详细信息row = 0col = 0for 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 += 1if col > 2:col = 0row += 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()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,'temp': temp_label,'weather': weather_label})def get_weather(self):city = self.city_entry.get()api_key = "你的API密钥"  # 替换为你的API密钥# 获取城市IDlocation_url = f"https://geoapi.qweather.com/v2/city/lookup?location={city}&key={api_key}"try:# 获取城市IDlocation_response = requests.get(location_url)location_data = json.loads(location_response.text)if location_data['code'] == '200' and location_data['location']:city_id = location_data['location'][0]['id']# 获取实时天气current_url = f"https://devapi.qweather.com/v7/weather/now?location={city_id}&key={api_key}"# 获取天气预报forecast_url = f"https://devapi.qweather.com/v7/weather/7d?location={city_id}&key={api_key}"# 获取当前天气response = requests.get(current_url)current_data = json.loads(response.text)if current_data['code'] == '200':now = current_data['now']# 更新当前天气信息self.city_label.config(text=f"{city}")self.temp_label.config(text=f"{now['temp']}°C")self.weather_label.config(text=f"{now['text']}")# 更新详细信息self.details["体感温度"].config(text=f"{now['feelsLike']}°C")self.details["湿度"].config(text=f"{now['humidity']}%")self.details["气压"].config(text=f"{now['pressure']}hPa")self.details["能见度"].config(text=f"{now['vis']}km")self.details["风向"].config(text=now['windDir'])self.details["风速"].config(text=f"{now['windSpeed']}km/h")# 获取天气预报forecast_response = requests.get(forecast_url)forecast_data = json.loads(forecast_response.text)if forecast_data['code'] == '200':daily_forecast = forecast_data['daily']for i, day in enumerate(daily_forecast[:5]):date = datetime.strptime(day['fxDate'], '%Y-%m-%d').strftime('%m/%d')self.forecast_days[i]['date'].config(text=date)self.forecast_days[i]['temp'].config(text=f"{day['tempMin']}°C - {day['tempMax']}°C")self.forecast_days[i]['weather'].config(text=day['textDay'])else:self.city_label.config(text="获取天气信息失败")else:self.city_label.config(text="未找到该城市")except Exception as e:print(f"错误信息: {str(e)}")self.city_label.config(text="获取天气信息失败")if __name__ == "__main__":root = tk.Tk()app = WeatherApp(root)root.mainloop()

三、注意事项

需要将代码中的api_key替换成你自己的,提前在和风天气官网注册一个账号并申请apikey

登录 | 和风天气

 

 


http://www.ppmy.cn/devtools/166825.html

相关文章

LINUX 安装1Panel

一、如果有外网快速安装(1Panel - 现代化、开源的 Linux 服务器运维管理面板 - 官网) curl -sSL https://resource.fit2cloud.com/1panel/package/quick_start.sh -o quick_start.sh && sh quick_start.sh 二、安装成功后,控制台会打…

Flutter 基础组件 Text 详解

目录 1. 引言 2. 基本使用 3. 自定义样式 4. 文本对齐与溢出控制 5. 外边距 5.1 使用 Container 包裹 5.2 使用 Padding 组件 5.3 在 Row/Column 中使用 5.4 动态边距调整 5.5 关键区别说明 5.6 设置 margin 无效 6. 结论 相关推荐 1. 引言 Text 组件是 Flutter 中…

word处理控件Aspose.Words教程:使用 Python 删除 Word 中的空白页

Aspose.Words 是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。 Aspose API支持流行文件格式处理,并…

【DevOps】通过 Azure DevOps 部署启用私有端点的应用服务

推荐超级课程: 本地离线DeepSeek AI方案部署实战教程【完全版】Docker快速入门到精通Kubernetes入门到大师通关课AWS云服务快速入门实战目录 **实验**测试 1:使用 Microsoft 托管代理部署测试 2:在 Linux VM (Ubuntu 20.04) 上使用自托管代理部署有一种常见的场景是,客户希…

Linux学习(十五)(故障排除(ICMP,Ping,Traceroute,网络统计,数据包分析))

故障排除是任何 Linux 用户或管理员的基本技能。这涉及识别和解决 Linux 系统中的问题。这些问题的范围包括常见的系统错误、硬件或软件问题、网络连接问题以及系统资源的管理。Linux 中的故障排除过程通常涉及使用命令行工具、检查系统和应用程序日志文件、了解系统进程&#…

【python】OpenCV—Hough Circle Transform

文章目录 1、功能描述2、代码实现3、效果展示4、完整代码5、涉及到的库函数6、参考 更多有趣的代码示例,可参考【Programming】 1、功能描述 2、代码实现 载入必要的库 import sys import cv2 as cv import numpy as np函数入口 if __name__ "__main__&qu…

Bash和Zsh在处理大文件时差异

在处理大文件时,Bash 和 Zsh 的差异主要体现在几个方面: 1. 脚本执行速度 Bash: 性能: Bash在执行脚本时通常表现良好,尤其是在处理大量数据或大文件时。Bash的脚本执行速度相对较快,适合大多数日常使用场景。优化: Bash在处理大…

【每日学点HarmonyOS Next知识】获取资源问题、软键盘弹起、swiper更新、C给图片设置位图、读取本地Json

1、HarmonyOS Resource获取value问题? 在resources-base-elements-string.json中创建了一个字符串常量,使用Text组件引用可以正常展示,但使用resourceManager.getSystemResourceManager().getStringValue()方法获取,提示9001001。…