投稿/コメントを表示します。

イトケンです。
今週の宿題提出させていただきます。
お天気デスクトップアプリを作ってみました。
メインフォームを作成し、
広島、山口、大阪、横浜ごとにラジオボタンを設置しました。
ラジオボタンで都市を選択し、実行ボタンを押すと
API連携で天気情報を取得し、結果を表示させるコードを
作成しました。
といってもAIに指示しただけです(;^_^。
明日も楽しみにしています♪

"""
tkinter シンプルな天気アプリ
"""
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
import urllib.request
import json


class WeatherApp(tk.Tk):
def __init__(self):
super().__init__()
self.title("天気予報アプリ")
self.geometry("300x250")

# 都市マッピング
self.cities = {
"広島市": "Hiroshima",
"山口市": "Yamaguchi",
"大阪市": "Osaka",
"横浜市": "Yokohama"
}

self.selected_city = tk.StringVar(value="広島市")
self.create_widgets()

def create_widgets(self):
tk.Label(self, text="都市を選択してください:", font=("Arial", 12)).pack(pady=10)

# ラジオボタン
for city in self.cities.keys():
tk.Radiobutton(self, text=city, variable=self.selected_city,
value=city, font=("Arial", 10)).pack(anchor="w", padx=40)

# 実行ボタン
tk.Button(self, text="天気を取得", command=self.get_weather,
font=("Arial", 12), bg="lightblue", padx=20, pady=5).pack(pady=20)

def get_weather(self):
city = self.selected_city.get()

try:
# API呼び出し
api_city = self.cities[city]
url = f"https://wttr.in/{api_city}?format=j1"

with urllib.request.urlopen(url, timeout=5) as response:
data = json.loads(response.read().decode('utf-8'))
current = data['current_condition'][0]
today = data['weather'][0]

weather_info = f"""
{city}の天気情報

日時: {datetime.now().strftime('%Y年%m月%d日 %H:%M')}
天気: {current['weatherDesc'][0]['value']}
気温: {current['temp_C']}℃
最高/最低: {today['maxtempC']}℃ / {today['mintempC']}℃
湿度: {current['humidity']}%
風速: {current['windspeedKmph']}km/h
"""

messagebox.showinfo(f"{city}の天気", weather_info)

except Exception as e:
messagebox.showerror("エラー",
f"天気情報の取得に失敗しました。\n\n"
f"エラー内容: {str(e)}\n\n"
f"・インターネット接続を確認してください\n"
f"・しばらく時間をおいて再試行してください")


if __name__ == "__main__":
app = WeatherApp()
app.mainloop()
2025/08/01 06:52