# 实时城市天气信息小项目实现


背景介绍

本项目旨在提供一个可独立运行的小型程序,用于实时获取城市天气信息并展示当前时间。该程序使用Python的requests库通过网络接口获取天气数据,无需依赖第三方服务或复杂框架。程序的核心功能包括:

  1. 输入城市名称和日期(示例:杭州、2023-04-05)
  2. 读取并解析天气数据(模拟API返回值)
  3. 显示当前时间及天气状态信息
  4. 独立运行,无需外部依赖

技术核心要点

  • 文件读写与数据处理:通过文件读取API返回的数据结构
  • 网络请求与接口调用:使用requests发送HTTP请求获取天气数据
  • GUI界面展示:通过Python的tkinter库创建可视化界面

代码实现

import requests
import tkinter as tk
from tkinter import messagebox

# API密钥(可替换为实际API密钥)
API_KEY = "your_api_key_here"

# 示例天气数据结构
def simulate_weather(city, date):
    url = f"http://api.weatherapi.com/data/2.5/weatherdata?q={city}&lang=en&appid={API_KEY}&formatted=1"
    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()

        # 处理天气数据
        weather = data['results']['element']
        weather_state = weather['condition']['name']
        current_time = date

        return {
            'city': city,
            'date': current_time,
            'weather': weather_state
        }
    except Exception as e:
        messagebox.showerror("错误", f"无法获取天气数据:{str(e)}")
        return None

# 创建GUI界面
def run_app():
    root = tk.Tk()
    root.title("城市天气小项目")

    # 输入框
    city_label = tk.Label(root, text="请输入城市名称:")
    city_entry = tk.Entry(root, width=20)
    date_label = tk.Label(root, text="请输入日期(格式:YYYY-MM-DD):")
    date_entry = tk.Entry(root, width=20)

    # 定时显示时间
    def update_time():
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        time_label = tk.Label(root, text=current_time)
        time_label.pack()

    # 按钮
    submit_button = tk.Button(root, text="获取天气", command=update_time)

    # 输入框和按钮
    city_label.pack()
    city_entry.pack()
    date_label.pack()
    date_entry.pack()
    submit_button.pack()

    # 初始日期
    initial_date = datetime.now().strftime("%Y-%m-%d %H:%M")
    time_label.config(text=initial_date)

    # 显示天气
    weather_data = simulate_weather("杭州", initial_date)

    if weather_data:
        messagebox.showinfo("天气信息", f"当前天气:{weather_data['weather']}\n日期:{weather_data['date']}")

    # 游出窗口
    root.mainloop()

if __name__ == "__main__":
    run_app()

总结

本项目通过Python的tkinter库创建了一个可独立运行的GUI界面,实现了城市天气信息的实时获取和展示。项目的核心技术包括:

  • 文件读写:通过文件读取API返回的数据结构
  • 网络请求:使用requests库发送HTTP请求获取天气数据
  • GUI界面展示:通过tkinter创建可视化界面

该程序可直接复制到Python环境运行,无需依赖第三方库或外部服务,能够满足用户的需求。通过模拟天气数据,展示了如何处理网络请求和数据解析,实现了功能完整的天气信息展示。


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注