Hướng dẫn tạo ứng dụng dự báo thời tiết với Python từ A-Z
Giới thiệu
Trong bài viết này, chúng ta sẽ xây dựng một ứng dụng dự báo thời tiết bằng Python sử dụng Tkinter để tạo giao diện và OpenWeatherMap API để lấy dữ liệu thời tiết.
1. Cấu trúc thư mục dự án
Chúng ta sẽ tổ chức dự án thành các tệp sau:
WeatherApp/
│── main.py # Tệp chính để chạy ứng dụng
│── gui.py # Xây dựng giao diện bằng Tkinter
│── weather.py # Xử lý lấy dữ liệu thời tiết
2. Lấy API Key từ OpenWeatherMap
- Truy cập https://openweathermap.org/api để đăng ký tài khoản và lấy API Key miễn phí.
3. Xử lý dữ liệu thời tiết
Tạo tệp weather.py để gọi API và lấy thông tin thời tiết.
# weather.py
import requests
API_KEY = "YOUR_API_KEY" # Thay YOUR_API_KEY bằng API thực tế của bạn
BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
def get_weather(city):
params = {"q": city, "appid": API_KEY, "units": "metric", "lang": "vi"}
response = requests.get(BASE_URL, params=params)
if response.status_code == 200:
data = response.json()
weather_info = {
"city": data["name"],
"temperature": data["main"]["temp"],
"description": data["weather"][0]["description"],
"humidity": data["main"]["humidity"],
"wind_speed": data["wind"]["speed"]
}
return weather_info
else:
return None
4. Thiết kế giao diện với Tkinter
Tạo tệp gui.py để xây dựng giao diện.
# gui.py
import tkinter as tk
from tkinter import messagebox
import weather
def get_weather_info():
city = city_entry.get()
if not city:
messagebox.showwarning("Lỗi", "Vui lòng nhập tên thành phố!")
return
weather_info = weather.get_weather(city)
if weather_info:
result_var.set(f"Thành phố: {weather_info['city']}\n"
f"Nhiệt độ: {weather_info['temperature']}°C\n"
f"Thời tiết: {weather_info['description']}\n"
f"Độ ẩm: {weather_info['humidity']}%\n"
f"Gió: {weather_info['wind_speed']} m/s")
else:
messagebox.showerror("Lỗi", "Không tìm thấy thông tin thời tiết!")
def create_gui(root):
global city_entry, result_var
tk.Label(root, text="Nhập tên thành phố:", font=("Arial", 12)).pack()
city_entry = tk.Entry(root, width=30)
city_entry.pack(pady=5)
tk.Button(root, text="Lấy thông tin thời tiết", command=get_weather_info).pack(pady=5)
result_var = tk.StringVar()
result_label = tk.Label(root, textvariable=result_var, font=("Arial", 12), justify="left")
result_label.pack(pady=10)
5. Chạy ứng dụng
Tạo tệp main.py để khởi chạy ứng dụng.
# main.py
import tkinter as tk
import gui
root = tk.Tk()
root.title("Dự báo thời tiết")
gui.create_gui(root)
root.mainloop()
Kết luận
Vậy là chúng ta đã hoàn thành một ứng dụng dự báo thời tiết với Python. Bạn có thể mở rộng thêm tính năng như hiển thị dự báo 5 ngày, biểu đồ nhiệt độ, hoặc lưu lịch sử tìm kiếm để làm ứng dụng hữu ích hơn!