中級者向け No.04

天気予報アプリ

OpenWeatherMap APIで現在・週間天気を取得して表示するアプリ。requestsライブラリとJSONデータ処理を学びます。

🎯 難易度: ★★☆ 📦 ライブラリ: tkinter(標準ライブラリ), requests ⏱️ 制作時間: 30〜90分

1. アプリ概要

OpenWeatherMap APIで現在・週間天気を取得して表示するアプリ。requestsライブラリとJSONデータ処理を学びます。

このアプリは中級カテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ)・requests で、難易度は ★★☆ です。

Pythonでは tkinter を使うことで、クロスプラットフォームなGUIアプリを簡単に作成できます。このアプリを通じて、ウィジェットの配置・イベント処理・データ管理など、GUI開発の実践的なスキルを習得できます。

ソースコードは完全な動作状態で提供しており、コピーしてそのまま実行できます。まずは実行して動作を確認し、その後コードを読んで仕組みを理解していきましょう。カスタマイズセクションでは機能拡張のアイデアも紹介しています。

GUIアプリ開発は、プログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。アプリを作ることで、変数・関数・クラス・イベント処理など、プログラミングの重要な概念が自然と身についていきます。このアプリをきっかけに、オリジナルアプリの開発にも挑戦してみてください。

2. 機能一覧

  • 天気予報アプリのメイン機能
  • 直感的なGUIインターフェース
  • 入力値のバリデーション
  • エラーハンドリング
  • 結果の見やすい表示
  • キーボードショートカット対応

3. 事前準備・環境

ℹ️
動作確認環境

Python 3.10 以上 / Windows・Mac・Linux すべて対応

以下の環境で動作確認しています。

  • Python 3.10 以上
  • OS: Windows 10/11・macOS 12+・Ubuntu 20.04+

4. 完全なソースコード

💡
コードのコピー方法

右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。

app04.py
import tkinter as tk
from tkinter import ttk, messagebox
import json
import urllib.request
import urllib.error
import urllib.parse
import threading
from datetime import datetime


class App04:
    """天気予報アプリ"""

    # OpenWeatherMap API(無料枠)
    API_KEY = "YOUR_API_KEY_HERE"
    BASE_URL = "https://api.openweathermap.org/data/2.5"

    WEATHER_ICONS = {
        "Clear": "☀️", "Clouds": "☁️", "Rain": "🌧️",
        "Drizzle": "🌦️", "Thunderstorm": "⛈️", "Snow": "❄️",
        "Mist": "🌫️", "Fog": "🌫️", "Haze": "🌫️",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("天気予報アプリ")
        self.root.geometry("600x540")
        self.root.configure(bg="#e8f4fd")
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#1976d2", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🌤️ 天気予報アプリ",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#1976d2", fg="white").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#e8f4fd", pady=10)
        search_frame.pack(fill=tk.X, padx=16)
        tk.Label(search_frame, text="都市名 (英語):",
                 bg="#e8f4fd", font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.city_var = tk.StringVar(value="Tokyo")
        city_entry = ttk.Entry(search_frame, textvariable=self.city_var,
                               font=("Arial", 12), width=20)
        city_entry.pack(side=tk.LEFT, padx=8)
        city_entry.bind("<Return>", lambda e: self._search())
        ttk.Button(search_frame, text="🔍 検索",
                   command=self._search).pack(side=tk.LEFT)

        # プリセット都市ボタン
        preset_frame = tk.Frame(self.root, bg="#e8f4fd")
        preset_frame.pack(fill=tk.X, padx=16)
        for city in ["Tokyo", "Osaka", "Sapporo", "Fukuoka", "London", "New York"]:
            tk.Button(preset_frame, text=city, bg="#90caf9",
                      relief=tk.FLAT, font=("Arial", 9), padx=6,
                      command=lambda c=city: (self.city_var.set(c), self._search())
                      ).pack(side=tk.LEFT, padx=2, pady=4)

        # 現在の天気パネル
        self.current_frame = ttk.LabelFrame(self.root, text="現在の天気", padding=12)
        self.current_frame.pack(fill=tk.X, padx=16, pady=6)
        self.weather_icon_label = tk.Label(self.current_frame, text="",
                                           font=("Segoe UI Emoji", 40),
                                           bg=self.current_frame.cget("background"))
        self.weather_icon_label.grid(row=0, column=0, rowspan=3, padx=12)
        self.city_label = tk.Label(self.current_frame, text="---",
                                   font=("Noto Sans JP", 18, "bold"),
                                   bg=self.current_frame.cget("background"))
        self.city_label.grid(row=0, column=1, sticky="w")
        self.temp_label = tk.Label(self.current_frame, text="--°C",
                                   font=("Arial", 28, "bold"), fg="#1976d2",
                                   bg=self.current_frame.cget("background"))
        self.temp_label.grid(row=1, column=1, sticky="w")
        self.desc_label = tk.Label(self.current_frame, text="",
                                   font=("Noto Sans JP", 11),
                                   bg=self.current_frame.cget("background"))
        self.desc_label.grid(row=2, column=1, sticky="w")

        # 詳細情報
        detail_frame = tk.Frame(self.current_frame,
                                bg=self.current_frame.cget("background"))
        detail_frame.grid(row=0, column=2, rowspan=3, padx=20, sticky="n")
        self.detail_labels = {}
        for i, key in enumerate(["湿度", "風速", "体感温度", "気圧"]):
            tk.Label(detail_frame, text=f"{key}:", font=("Arial", 10),
                     bg=detail_frame.cget("bg")).grid(row=i, column=0, sticky="w", pady=2)
            lbl = tk.Label(detail_frame, text="--", font=("Arial", 10, "bold"),
                           bg=detail_frame.cget("bg"), fg="#1976d2")
            lbl.grid(row=i, column=1, sticky="w", padx=8)
            self.detail_labels[key] = lbl

        # 5日間予報
        forecast_frame = ttk.LabelFrame(self.root, text="5日間予報", padding=8)
        forecast_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 8))
        self.forecast_canvas = tk.Canvas(forecast_frame, bg="#f5f9ff",
                                         highlightthickness=0, height=160)
        self.forecast_canvas.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="都市名を入力して検索してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _search(self):
        city = self.city_var.get().strip()
        if not city:
            return
        self.status_var.set(f"取得中: {city} ...")
        threading.Thread(target=self._fetch_weather, args=(city,),
                         daemon=True).start()

    def _fetch_weather(self, city):
        try:
            # 現在天気
            url = (f"{self.BASE_URL}/weather?q={urllib.parse.quote(city)}"
                   f"&appid={self.API_KEY}&units=metric&lang=ja")
            with urllib.request.urlopen(url, timeout=10) as resp:
                data = json.loads(resp.read())
            self.root.after(0, self._update_current, data)

            # 5日間予報
            url5 = (f"{self.BASE_URL}/forecast?q={urllib.parse.quote(city)}"
                    f"&appid={self.API_KEY}&units=metric&lang=ja&cnt=40")
            with urllib.request.urlopen(url5, timeout=10) as resp:
                forecast = json.loads(resp.read())
            self.root.after(0, self._update_forecast, forecast)
        except urllib.error.HTTPError as e:
            if e.code == 401:
                msg = "APIキーが無効です。YOUR_API_KEY_HEREを実際のキーに置き換えてください"
            elif e.code == 404:
                msg = f"都市が見つかりません: {city}"
            else:
                msg = f"HTTPエラー: {e.code}"
            self.root.after(0, self._show_demo, city, msg)
        except Exception as e:
            self.root.after(0, self._show_demo, city, str(e))

    def _update_current(self, data):
        name = data["name"]
        temp = data["main"]["temp"]
        feels = data["main"]["feels_like"]
        hum = data["main"]["humidity"]
        wind = data["wind"]["speed"]
        pres = data["main"]["pressure"]
        desc = data["weather"][0]["description"]
        main = data["weather"][0]["main"]
        icon = self.WEATHER_ICONS.get(main, "🌡️")

        self.weather_icon_label.config(text=icon)
        self.city_label.config(text=name)
        self.temp_label.config(text=f"{temp:.1f}°C")
        self.desc_label.config(text=desc)
        self.detail_labels["湿度"].config(text=f"{hum}%")
        self.detail_labels["風速"].config(text=f"{wind} m/s")
        self.detail_labels["体感温度"].config(text=f"{feels:.1f}°C")
        self.detail_labels["気圧"].config(text=f"{pres} hPa")
        self.status_var.set(f"取得完了: {name}  ({datetime.now().strftime('%H:%M')})")

    def _update_forecast(self, data):
        self.forecast_canvas.delete("all")
        # 1日1エントリに集約(正午データ優先)
        days = {}
        for item in data["list"]:
            date = item["dt_txt"][:10]
            hour = item["dt_txt"][11:13]
            if date not in days or hour == "12":
                days[date] = item
        entries = list(days.values())[:5]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // max(len(entries), 1)
        for i, item in enumerate(entries):
            x = i * col_w + col_w // 2
            date = item["dt_txt"][:10]
            weekday = ["月", "火", "水", "木", "金", "土", "日"][
                datetime.strptime(date, "%Y-%m-%d").weekday()]
            temp = item["main"]["temp"]
            main = item["weather"][0]["main"]
            icon = self.WEATHER_ICONS.get(main, "🌡️")
            desc = item["weather"][0]["description"]

            self.forecast_canvas.create_text(x, 20, text=f"{date[5:]} ({weekday})",
                                             font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=f"{temp:.0f}°C",
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")
            if i < len(entries) - 1:
                self.forecast_canvas.create_line(
                    (i+1)*col_w, 10, (i+1)*col_w, 140, fill="#ccc")

    def _show_demo(self, city, error_msg):
        """APIキー未設定時はデモデータを表示"""
        self.weather_icon_label.config(text="☀️")
        self.city_label.config(text=f"{city} (デモ)")
        self.temp_label.config(text="22.5°C")
        self.desc_label.config(text="晴れ (デモデータ)")
        self.detail_labels["湿度"].config(text="55%")
        self.detail_labels["風速"].config(text="3.2 m/s")
        self.detail_labels["体感温度"].config(text="21.8°C")
        self.detail_labels["気圧"].config(text="1013 hPa")
        self.status_var.set(f"⚠ {error_msg}  ※デモ表示中")

        # デモ予報
        self.forecast_canvas.delete("all")
        demo = [("☀️", "22°C", "晴れ"), ("⛅", "19°C", "曇り"),
                ("🌧️", "16°C", "雨"), ("☁️", "18°C", "曇り"),
                ("☀️", "24°C", "晴れ")]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // 5
        from datetime import timedelta, date
        for i, (icon, temp, desc) in enumerate(demo):
            d = date.today() + timedelta(days=i)
            weekday = ["月", "火", "水", "木", "金", "土", "日"][d.weekday()]
            x = i * col_w + col_w // 2
            self.forecast_canvas.create_text(
                x, 20, text=f"{d.strftime('%m/%d')} ({weekday})", font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=temp,
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")


if __name__ == "__main__":
    root = tk.Tk()
    app = App04(root)
    root.mainloop()

5. コード解説

天気予報アプリのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

クラス設計とコンストラクタ

App04クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。

import tkinter as tk
from tkinter import ttk, messagebox
import json
import urllib.request
import urllib.error
import urllib.parse
import threading
from datetime import datetime


class App04:
    """天気予報アプリ"""

    # OpenWeatherMap API(無料枠)
    API_KEY = "YOUR_API_KEY_HERE"
    BASE_URL = "https://api.openweathermap.org/data/2.5"

    WEATHER_ICONS = {
        "Clear": "☀️", "Clouds": "☁️", "Rain": "🌧️",
        "Drizzle": "🌦️", "Thunderstorm": "⛈️", "Snow": "❄️",
        "Mist": "🌫️", "Fog": "🌫️", "Haze": "🌫️",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("天気予報アプリ")
        self.root.geometry("600x540")
        self.root.configure(bg="#e8f4fd")
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#1976d2", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🌤️ 天気予報アプリ",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#1976d2", fg="white").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#e8f4fd", pady=10)
        search_frame.pack(fill=tk.X, padx=16)
        tk.Label(search_frame, text="都市名 (英語):",
                 bg="#e8f4fd", font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.city_var = tk.StringVar(value="Tokyo")
        city_entry = ttk.Entry(search_frame, textvariable=self.city_var,
                               font=("Arial", 12), width=20)
        city_entry.pack(side=tk.LEFT, padx=8)
        city_entry.bind("<Return>", lambda e: self._search())
        ttk.Button(search_frame, text="🔍 検索",
                   command=self._search).pack(side=tk.LEFT)

        # プリセット都市ボタン
        preset_frame = tk.Frame(self.root, bg="#e8f4fd")
        preset_frame.pack(fill=tk.X, padx=16)
        for city in ["Tokyo", "Osaka", "Sapporo", "Fukuoka", "London", "New York"]:
            tk.Button(preset_frame, text=city, bg="#90caf9",
                      relief=tk.FLAT, font=("Arial", 9), padx=6,
                      command=lambda c=city: (self.city_var.set(c), self._search())
                      ).pack(side=tk.LEFT, padx=2, pady=4)

        # 現在の天気パネル
        self.current_frame = ttk.LabelFrame(self.root, text="現在の天気", padding=12)
        self.current_frame.pack(fill=tk.X, padx=16, pady=6)
        self.weather_icon_label = tk.Label(self.current_frame, text="",
                                           font=("Segoe UI Emoji", 40),
                                           bg=self.current_frame.cget("background"))
        self.weather_icon_label.grid(row=0, column=0, rowspan=3, padx=12)
        self.city_label = tk.Label(self.current_frame, text="---",
                                   font=("Noto Sans JP", 18, "bold"),
                                   bg=self.current_frame.cget("background"))
        self.city_label.grid(row=0, column=1, sticky="w")
        self.temp_label = tk.Label(self.current_frame, text="--°C",
                                   font=("Arial", 28, "bold"), fg="#1976d2",
                                   bg=self.current_frame.cget("background"))
        self.temp_label.grid(row=1, column=1, sticky="w")
        self.desc_label = tk.Label(self.current_frame, text="",
                                   font=("Noto Sans JP", 11),
                                   bg=self.current_frame.cget("background"))
        self.desc_label.grid(row=2, column=1, sticky="w")

        # 詳細情報
        detail_frame = tk.Frame(self.current_frame,
                                bg=self.current_frame.cget("background"))
        detail_frame.grid(row=0, column=2, rowspan=3, padx=20, sticky="n")
        self.detail_labels = {}
        for i, key in enumerate(["湿度", "風速", "体感温度", "気圧"]):
            tk.Label(detail_frame, text=f"{key}:", font=("Arial", 10),
                     bg=detail_frame.cget("bg")).grid(row=i, column=0, sticky="w", pady=2)
            lbl = tk.Label(detail_frame, text="--", font=("Arial", 10, "bold"),
                           bg=detail_frame.cget("bg"), fg="#1976d2")
            lbl.grid(row=i, column=1, sticky="w", padx=8)
            self.detail_labels[key] = lbl

        # 5日間予報
        forecast_frame = ttk.LabelFrame(self.root, text="5日間予報", padding=8)
        forecast_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 8))
        self.forecast_canvas = tk.Canvas(forecast_frame, bg="#f5f9ff",
                                         highlightthickness=0, height=160)
        self.forecast_canvas.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="都市名を入力して検索してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _search(self):
        city = self.city_var.get().strip()
        if not city:
            return
        self.status_var.set(f"取得中: {city} ...")
        threading.Thread(target=self._fetch_weather, args=(city,),
                         daemon=True).start()

    def _fetch_weather(self, city):
        try:
            # 現在天気
            url = (f"{self.BASE_URL}/weather?q={urllib.parse.quote(city)}"
                   f"&appid={self.API_KEY}&units=metric&lang=ja")
            with urllib.request.urlopen(url, timeout=10) as resp:
                data = json.loads(resp.read())
            self.root.after(0, self._update_current, data)

            # 5日間予報
            url5 = (f"{self.BASE_URL}/forecast?q={urllib.parse.quote(city)}"
                    f"&appid={self.API_KEY}&units=metric&lang=ja&cnt=40")
            with urllib.request.urlopen(url5, timeout=10) as resp:
                forecast = json.loads(resp.read())
            self.root.after(0, self._update_forecast, forecast)
        except urllib.error.HTTPError as e:
            if e.code == 401:
                msg = "APIキーが無効です。YOUR_API_KEY_HEREを実際のキーに置き換えてください"
            elif e.code == 404:
                msg = f"都市が見つかりません: {city}"
            else:
                msg = f"HTTPエラー: {e.code}"
            self.root.after(0, self._show_demo, city, msg)
        except Exception as e:
            self.root.after(0, self._show_demo, city, str(e))

    def _update_current(self, data):
        name = data["name"]
        temp = data["main"]["temp"]
        feels = data["main"]["feels_like"]
        hum = data["main"]["humidity"]
        wind = data["wind"]["speed"]
        pres = data["main"]["pressure"]
        desc = data["weather"][0]["description"]
        main = data["weather"][0]["main"]
        icon = self.WEATHER_ICONS.get(main, "🌡️")

        self.weather_icon_label.config(text=icon)
        self.city_label.config(text=name)
        self.temp_label.config(text=f"{temp:.1f}°C")
        self.desc_label.config(text=desc)
        self.detail_labels["湿度"].config(text=f"{hum}%")
        self.detail_labels["風速"].config(text=f"{wind} m/s")
        self.detail_labels["体感温度"].config(text=f"{feels:.1f}°C")
        self.detail_labels["気圧"].config(text=f"{pres} hPa")
        self.status_var.set(f"取得完了: {name}  ({datetime.now().strftime('%H:%M')})")

    def _update_forecast(self, data):
        self.forecast_canvas.delete("all")
        # 1日1エントリに集約(正午データ優先)
        days = {}
        for item in data["list"]:
            date = item["dt_txt"][:10]
            hour = item["dt_txt"][11:13]
            if date not in days or hour == "12":
                days[date] = item
        entries = list(days.values())[:5]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // max(len(entries), 1)
        for i, item in enumerate(entries):
            x = i * col_w + col_w // 2
            date = item["dt_txt"][:10]
            weekday = ["月", "火", "水", "木", "金", "土", "日"][
                datetime.strptime(date, "%Y-%m-%d").weekday()]
            temp = item["main"]["temp"]
            main = item["weather"][0]["main"]
            icon = self.WEATHER_ICONS.get(main, "🌡️")
            desc = item["weather"][0]["description"]

            self.forecast_canvas.create_text(x, 20, text=f"{date[5:]} ({weekday})",
                                             font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=f"{temp:.0f}°C",
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")
            if i < len(entries) - 1:
                self.forecast_canvas.create_line(
                    (i+1)*col_w, 10, (i+1)*col_w, 140, fill="#ccc")

    def _show_demo(self, city, error_msg):
        """APIキー未設定時はデモデータを表示"""
        self.weather_icon_label.config(text="☀️")
        self.city_label.config(text=f"{city} (デモ)")
        self.temp_label.config(text="22.5°C")
        self.desc_label.config(text="晴れ (デモデータ)")
        self.detail_labels["湿度"].config(text="55%")
        self.detail_labels["風速"].config(text="3.2 m/s")
        self.detail_labels["体感温度"].config(text="21.8°C")
        self.detail_labels["気圧"].config(text="1013 hPa")
        self.status_var.set(f"⚠ {error_msg}  ※デモ表示中")

        # デモ予報
        self.forecast_canvas.delete("all")
        demo = [("☀️", "22°C", "晴れ"), ("⛅", "19°C", "曇り"),
                ("🌧️", "16°C", "雨"), ("☁️", "18°C", "曇り"),
                ("☀️", "24°C", "晴れ")]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // 5
        from datetime import timedelta, date
        for i, (icon, temp, desc) in enumerate(demo):
            d = date.today() + timedelta(days=i)
            weekday = ["月", "火", "水", "木", "金", "土", "日"][d.weekday()]
            x = i * col_w + col_w // 2
            self.forecast_canvas.create_text(
                x, 20, text=f"{d.strftime('%m/%d')} ({weekday})", font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=temp,
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")


if __name__ == "__main__":
    root = tk.Tk()
    app = App04(root)
    root.mainloop()

LabelFrameによるセクション分け

ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。

import tkinter as tk
from tkinter import ttk, messagebox
import json
import urllib.request
import urllib.error
import urllib.parse
import threading
from datetime import datetime


class App04:
    """天気予報アプリ"""

    # OpenWeatherMap API(無料枠)
    API_KEY = "YOUR_API_KEY_HERE"
    BASE_URL = "https://api.openweathermap.org/data/2.5"

    WEATHER_ICONS = {
        "Clear": "☀️", "Clouds": "☁️", "Rain": "🌧️",
        "Drizzle": "🌦️", "Thunderstorm": "⛈️", "Snow": "❄️",
        "Mist": "🌫️", "Fog": "🌫️", "Haze": "🌫️",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("天気予報アプリ")
        self.root.geometry("600x540")
        self.root.configure(bg="#e8f4fd")
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#1976d2", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🌤️ 天気予報アプリ",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#1976d2", fg="white").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#e8f4fd", pady=10)
        search_frame.pack(fill=tk.X, padx=16)
        tk.Label(search_frame, text="都市名 (英語):",
                 bg="#e8f4fd", font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.city_var = tk.StringVar(value="Tokyo")
        city_entry = ttk.Entry(search_frame, textvariable=self.city_var,
                               font=("Arial", 12), width=20)
        city_entry.pack(side=tk.LEFT, padx=8)
        city_entry.bind("<Return>", lambda e: self._search())
        ttk.Button(search_frame, text="🔍 検索",
                   command=self._search).pack(side=tk.LEFT)

        # プリセット都市ボタン
        preset_frame = tk.Frame(self.root, bg="#e8f4fd")
        preset_frame.pack(fill=tk.X, padx=16)
        for city in ["Tokyo", "Osaka", "Sapporo", "Fukuoka", "London", "New York"]:
            tk.Button(preset_frame, text=city, bg="#90caf9",
                      relief=tk.FLAT, font=("Arial", 9), padx=6,
                      command=lambda c=city: (self.city_var.set(c), self._search())
                      ).pack(side=tk.LEFT, padx=2, pady=4)

        # 現在の天気パネル
        self.current_frame = ttk.LabelFrame(self.root, text="現在の天気", padding=12)
        self.current_frame.pack(fill=tk.X, padx=16, pady=6)
        self.weather_icon_label = tk.Label(self.current_frame, text="",
                                           font=("Segoe UI Emoji", 40),
                                           bg=self.current_frame.cget("background"))
        self.weather_icon_label.grid(row=0, column=0, rowspan=3, padx=12)
        self.city_label = tk.Label(self.current_frame, text="---",
                                   font=("Noto Sans JP", 18, "bold"),
                                   bg=self.current_frame.cget("background"))
        self.city_label.grid(row=0, column=1, sticky="w")
        self.temp_label = tk.Label(self.current_frame, text="--°C",
                                   font=("Arial", 28, "bold"), fg="#1976d2",
                                   bg=self.current_frame.cget("background"))
        self.temp_label.grid(row=1, column=1, sticky="w")
        self.desc_label = tk.Label(self.current_frame, text="",
                                   font=("Noto Sans JP", 11),
                                   bg=self.current_frame.cget("background"))
        self.desc_label.grid(row=2, column=1, sticky="w")

        # 詳細情報
        detail_frame = tk.Frame(self.current_frame,
                                bg=self.current_frame.cget("background"))
        detail_frame.grid(row=0, column=2, rowspan=3, padx=20, sticky="n")
        self.detail_labels = {}
        for i, key in enumerate(["湿度", "風速", "体感温度", "気圧"]):
            tk.Label(detail_frame, text=f"{key}:", font=("Arial", 10),
                     bg=detail_frame.cget("bg")).grid(row=i, column=0, sticky="w", pady=2)
            lbl = tk.Label(detail_frame, text="--", font=("Arial", 10, "bold"),
                           bg=detail_frame.cget("bg"), fg="#1976d2")
            lbl.grid(row=i, column=1, sticky="w", padx=8)
            self.detail_labels[key] = lbl

        # 5日間予報
        forecast_frame = ttk.LabelFrame(self.root, text="5日間予報", padding=8)
        forecast_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 8))
        self.forecast_canvas = tk.Canvas(forecast_frame, bg="#f5f9ff",
                                         highlightthickness=0, height=160)
        self.forecast_canvas.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="都市名を入力して検索してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _search(self):
        city = self.city_var.get().strip()
        if not city:
            return
        self.status_var.set(f"取得中: {city} ...")
        threading.Thread(target=self._fetch_weather, args=(city,),
                         daemon=True).start()

    def _fetch_weather(self, city):
        try:
            # 現在天気
            url = (f"{self.BASE_URL}/weather?q={urllib.parse.quote(city)}"
                   f"&appid={self.API_KEY}&units=metric&lang=ja")
            with urllib.request.urlopen(url, timeout=10) as resp:
                data = json.loads(resp.read())
            self.root.after(0, self._update_current, data)

            # 5日間予報
            url5 = (f"{self.BASE_URL}/forecast?q={urllib.parse.quote(city)}"
                    f"&appid={self.API_KEY}&units=metric&lang=ja&cnt=40")
            with urllib.request.urlopen(url5, timeout=10) as resp:
                forecast = json.loads(resp.read())
            self.root.after(0, self._update_forecast, forecast)
        except urllib.error.HTTPError as e:
            if e.code == 401:
                msg = "APIキーが無効です。YOUR_API_KEY_HEREを実際のキーに置き換えてください"
            elif e.code == 404:
                msg = f"都市が見つかりません: {city}"
            else:
                msg = f"HTTPエラー: {e.code}"
            self.root.after(0, self._show_demo, city, msg)
        except Exception as e:
            self.root.after(0, self._show_demo, city, str(e))

    def _update_current(self, data):
        name = data["name"]
        temp = data["main"]["temp"]
        feels = data["main"]["feels_like"]
        hum = data["main"]["humidity"]
        wind = data["wind"]["speed"]
        pres = data["main"]["pressure"]
        desc = data["weather"][0]["description"]
        main = data["weather"][0]["main"]
        icon = self.WEATHER_ICONS.get(main, "🌡️")

        self.weather_icon_label.config(text=icon)
        self.city_label.config(text=name)
        self.temp_label.config(text=f"{temp:.1f}°C")
        self.desc_label.config(text=desc)
        self.detail_labels["湿度"].config(text=f"{hum}%")
        self.detail_labels["風速"].config(text=f"{wind} m/s")
        self.detail_labels["体感温度"].config(text=f"{feels:.1f}°C")
        self.detail_labels["気圧"].config(text=f"{pres} hPa")
        self.status_var.set(f"取得完了: {name}  ({datetime.now().strftime('%H:%M')})")

    def _update_forecast(self, data):
        self.forecast_canvas.delete("all")
        # 1日1エントリに集約(正午データ優先)
        days = {}
        for item in data["list"]:
            date = item["dt_txt"][:10]
            hour = item["dt_txt"][11:13]
            if date not in days or hour == "12":
                days[date] = item
        entries = list(days.values())[:5]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // max(len(entries), 1)
        for i, item in enumerate(entries):
            x = i * col_w + col_w // 2
            date = item["dt_txt"][:10]
            weekday = ["月", "火", "水", "木", "金", "土", "日"][
                datetime.strptime(date, "%Y-%m-%d").weekday()]
            temp = item["main"]["temp"]
            main = item["weather"][0]["main"]
            icon = self.WEATHER_ICONS.get(main, "🌡️")
            desc = item["weather"][0]["description"]

            self.forecast_canvas.create_text(x, 20, text=f"{date[5:]} ({weekday})",
                                             font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=f"{temp:.0f}°C",
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")
            if i < len(entries) - 1:
                self.forecast_canvas.create_line(
                    (i+1)*col_w, 10, (i+1)*col_w, 140, fill="#ccc")

    def _show_demo(self, city, error_msg):
        """APIキー未設定時はデモデータを表示"""
        self.weather_icon_label.config(text="☀️")
        self.city_label.config(text=f"{city} (デモ)")
        self.temp_label.config(text="22.5°C")
        self.desc_label.config(text="晴れ (デモデータ)")
        self.detail_labels["湿度"].config(text="55%")
        self.detail_labels["風速"].config(text="3.2 m/s")
        self.detail_labels["体感温度"].config(text="21.8°C")
        self.detail_labels["気圧"].config(text="1013 hPa")
        self.status_var.set(f"⚠ {error_msg}  ※デモ表示中")

        # デモ予報
        self.forecast_canvas.delete("all")
        demo = [("☀️", "22°C", "晴れ"), ("⛅", "19°C", "曇り"),
                ("🌧️", "16°C", "雨"), ("☁️", "18°C", "曇り"),
                ("☀️", "24°C", "晴れ")]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // 5
        from datetime import timedelta, date
        for i, (icon, temp, desc) in enumerate(demo):
            d = date.today() + timedelta(days=i)
            weekday = ["月", "火", "水", "木", "金", "土", "日"][d.weekday()]
            x = i * col_w + col_w // 2
            self.forecast_canvas.create_text(
                x, 20, text=f"{d.strftime('%m/%d')} ({weekday})", font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=temp,
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")


if __name__ == "__main__":
    root = tk.Tk()
    app = App04(root)
    root.mainloop()

Entryウィジェットとイベントバインド

ttk.Entryで入力フィールドを作成します。bind('', ...)でEnterキー押下時に処理を実行できます。これにより、マウスを使わずキーボードだけで操作できるUXが実現できます。

import tkinter as tk
from tkinter import ttk, messagebox
import json
import urllib.request
import urllib.error
import urllib.parse
import threading
from datetime import datetime


class App04:
    """天気予報アプリ"""

    # OpenWeatherMap API(無料枠)
    API_KEY = "YOUR_API_KEY_HERE"
    BASE_URL = "https://api.openweathermap.org/data/2.5"

    WEATHER_ICONS = {
        "Clear": "☀️", "Clouds": "☁️", "Rain": "🌧️",
        "Drizzle": "🌦️", "Thunderstorm": "⛈️", "Snow": "❄️",
        "Mist": "🌫️", "Fog": "🌫️", "Haze": "🌫️",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("天気予報アプリ")
        self.root.geometry("600x540")
        self.root.configure(bg="#e8f4fd")
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#1976d2", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🌤️ 天気予報アプリ",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#1976d2", fg="white").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#e8f4fd", pady=10)
        search_frame.pack(fill=tk.X, padx=16)
        tk.Label(search_frame, text="都市名 (英語):",
                 bg="#e8f4fd", font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.city_var = tk.StringVar(value="Tokyo")
        city_entry = ttk.Entry(search_frame, textvariable=self.city_var,
                               font=("Arial", 12), width=20)
        city_entry.pack(side=tk.LEFT, padx=8)
        city_entry.bind("<Return>", lambda e: self._search())
        ttk.Button(search_frame, text="🔍 検索",
                   command=self._search).pack(side=tk.LEFT)

        # プリセット都市ボタン
        preset_frame = tk.Frame(self.root, bg="#e8f4fd")
        preset_frame.pack(fill=tk.X, padx=16)
        for city in ["Tokyo", "Osaka", "Sapporo", "Fukuoka", "London", "New York"]:
            tk.Button(preset_frame, text=city, bg="#90caf9",
                      relief=tk.FLAT, font=("Arial", 9), padx=6,
                      command=lambda c=city: (self.city_var.set(c), self._search())
                      ).pack(side=tk.LEFT, padx=2, pady=4)

        # 現在の天気パネル
        self.current_frame = ttk.LabelFrame(self.root, text="現在の天気", padding=12)
        self.current_frame.pack(fill=tk.X, padx=16, pady=6)
        self.weather_icon_label = tk.Label(self.current_frame, text="",
                                           font=("Segoe UI Emoji", 40),
                                           bg=self.current_frame.cget("background"))
        self.weather_icon_label.grid(row=0, column=0, rowspan=3, padx=12)
        self.city_label = tk.Label(self.current_frame, text="---",
                                   font=("Noto Sans JP", 18, "bold"),
                                   bg=self.current_frame.cget("background"))
        self.city_label.grid(row=0, column=1, sticky="w")
        self.temp_label = tk.Label(self.current_frame, text="--°C",
                                   font=("Arial", 28, "bold"), fg="#1976d2",
                                   bg=self.current_frame.cget("background"))
        self.temp_label.grid(row=1, column=1, sticky="w")
        self.desc_label = tk.Label(self.current_frame, text="",
                                   font=("Noto Sans JP", 11),
                                   bg=self.current_frame.cget("background"))
        self.desc_label.grid(row=2, column=1, sticky="w")

        # 詳細情報
        detail_frame = tk.Frame(self.current_frame,
                                bg=self.current_frame.cget("background"))
        detail_frame.grid(row=0, column=2, rowspan=3, padx=20, sticky="n")
        self.detail_labels = {}
        for i, key in enumerate(["湿度", "風速", "体感温度", "気圧"]):
            tk.Label(detail_frame, text=f"{key}:", font=("Arial", 10),
                     bg=detail_frame.cget("bg")).grid(row=i, column=0, sticky="w", pady=2)
            lbl = tk.Label(detail_frame, text="--", font=("Arial", 10, "bold"),
                           bg=detail_frame.cget("bg"), fg="#1976d2")
            lbl.grid(row=i, column=1, sticky="w", padx=8)
            self.detail_labels[key] = lbl

        # 5日間予報
        forecast_frame = ttk.LabelFrame(self.root, text="5日間予報", padding=8)
        forecast_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 8))
        self.forecast_canvas = tk.Canvas(forecast_frame, bg="#f5f9ff",
                                         highlightthickness=0, height=160)
        self.forecast_canvas.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="都市名を入力して検索してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _search(self):
        city = self.city_var.get().strip()
        if not city:
            return
        self.status_var.set(f"取得中: {city} ...")
        threading.Thread(target=self._fetch_weather, args=(city,),
                         daemon=True).start()

    def _fetch_weather(self, city):
        try:
            # 現在天気
            url = (f"{self.BASE_URL}/weather?q={urllib.parse.quote(city)}"
                   f"&appid={self.API_KEY}&units=metric&lang=ja")
            with urllib.request.urlopen(url, timeout=10) as resp:
                data = json.loads(resp.read())
            self.root.after(0, self._update_current, data)

            # 5日間予報
            url5 = (f"{self.BASE_URL}/forecast?q={urllib.parse.quote(city)}"
                    f"&appid={self.API_KEY}&units=metric&lang=ja&cnt=40")
            with urllib.request.urlopen(url5, timeout=10) as resp:
                forecast = json.loads(resp.read())
            self.root.after(0, self._update_forecast, forecast)
        except urllib.error.HTTPError as e:
            if e.code == 401:
                msg = "APIキーが無効です。YOUR_API_KEY_HEREを実際のキーに置き換えてください"
            elif e.code == 404:
                msg = f"都市が見つかりません: {city}"
            else:
                msg = f"HTTPエラー: {e.code}"
            self.root.after(0, self._show_demo, city, msg)
        except Exception as e:
            self.root.after(0, self._show_demo, city, str(e))

    def _update_current(self, data):
        name = data["name"]
        temp = data["main"]["temp"]
        feels = data["main"]["feels_like"]
        hum = data["main"]["humidity"]
        wind = data["wind"]["speed"]
        pres = data["main"]["pressure"]
        desc = data["weather"][0]["description"]
        main = data["weather"][0]["main"]
        icon = self.WEATHER_ICONS.get(main, "🌡️")

        self.weather_icon_label.config(text=icon)
        self.city_label.config(text=name)
        self.temp_label.config(text=f"{temp:.1f}°C")
        self.desc_label.config(text=desc)
        self.detail_labels["湿度"].config(text=f"{hum}%")
        self.detail_labels["風速"].config(text=f"{wind} m/s")
        self.detail_labels["体感温度"].config(text=f"{feels:.1f}°C")
        self.detail_labels["気圧"].config(text=f"{pres} hPa")
        self.status_var.set(f"取得完了: {name}  ({datetime.now().strftime('%H:%M')})")

    def _update_forecast(self, data):
        self.forecast_canvas.delete("all")
        # 1日1エントリに集約(正午データ優先)
        days = {}
        for item in data["list"]:
            date = item["dt_txt"][:10]
            hour = item["dt_txt"][11:13]
            if date not in days or hour == "12":
                days[date] = item
        entries = list(days.values())[:5]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // max(len(entries), 1)
        for i, item in enumerate(entries):
            x = i * col_w + col_w // 2
            date = item["dt_txt"][:10]
            weekday = ["月", "火", "水", "木", "金", "土", "日"][
                datetime.strptime(date, "%Y-%m-%d").weekday()]
            temp = item["main"]["temp"]
            main = item["weather"][0]["main"]
            icon = self.WEATHER_ICONS.get(main, "🌡️")
            desc = item["weather"][0]["description"]

            self.forecast_canvas.create_text(x, 20, text=f"{date[5:]} ({weekday})",
                                             font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=f"{temp:.0f}°C",
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")
            if i < len(entries) - 1:
                self.forecast_canvas.create_line(
                    (i+1)*col_w, 10, (i+1)*col_w, 140, fill="#ccc")

    def _show_demo(self, city, error_msg):
        """APIキー未設定時はデモデータを表示"""
        self.weather_icon_label.config(text="☀️")
        self.city_label.config(text=f"{city} (デモ)")
        self.temp_label.config(text="22.5°C")
        self.desc_label.config(text="晴れ (デモデータ)")
        self.detail_labels["湿度"].config(text="55%")
        self.detail_labels["風速"].config(text="3.2 m/s")
        self.detail_labels["体感温度"].config(text="21.8°C")
        self.detail_labels["気圧"].config(text="1013 hPa")
        self.status_var.set(f"⚠ {error_msg}  ※デモ表示中")

        # デモ予報
        self.forecast_canvas.delete("all")
        demo = [("☀️", "22°C", "晴れ"), ("⛅", "19°C", "曇り"),
                ("🌧️", "16°C", "雨"), ("☁️", "18°C", "曇り"),
                ("☀️", "24°C", "晴れ")]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // 5
        from datetime import timedelta, date
        for i, (icon, temp, desc) in enumerate(demo):
            d = date.today() + timedelta(days=i)
            weekday = ["月", "火", "水", "木", "金", "土", "日"][d.weekday()]
            x = i * col_w + col_w // 2
            self.forecast_canvas.create_text(
                x, 20, text=f"{d.strftime('%m/%d')} ({weekday})", font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=temp,
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")


if __name__ == "__main__":
    root = tk.Tk()
    app = App04(root)
    root.mainloop()

Textウィジェットでの結果表示

結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。

import tkinter as tk
from tkinter import ttk, messagebox
import json
import urllib.request
import urllib.error
import urllib.parse
import threading
from datetime import datetime


class App04:
    """天気予報アプリ"""

    # OpenWeatherMap API(無料枠)
    API_KEY = "YOUR_API_KEY_HERE"
    BASE_URL = "https://api.openweathermap.org/data/2.5"

    WEATHER_ICONS = {
        "Clear": "☀️", "Clouds": "☁️", "Rain": "🌧️",
        "Drizzle": "🌦️", "Thunderstorm": "⛈️", "Snow": "❄️",
        "Mist": "🌫️", "Fog": "🌫️", "Haze": "🌫️",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("天気予報アプリ")
        self.root.geometry("600x540")
        self.root.configure(bg="#e8f4fd")
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#1976d2", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🌤️ 天気予報アプリ",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#1976d2", fg="white").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#e8f4fd", pady=10)
        search_frame.pack(fill=tk.X, padx=16)
        tk.Label(search_frame, text="都市名 (英語):",
                 bg="#e8f4fd", font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.city_var = tk.StringVar(value="Tokyo")
        city_entry = ttk.Entry(search_frame, textvariable=self.city_var,
                               font=("Arial", 12), width=20)
        city_entry.pack(side=tk.LEFT, padx=8)
        city_entry.bind("<Return>", lambda e: self._search())
        ttk.Button(search_frame, text="🔍 検索",
                   command=self._search).pack(side=tk.LEFT)

        # プリセット都市ボタン
        preset_frame = tk.Frame(self.root, bg="#e8f4fd")
        preset_frame.pack(fill=tk.X, padx=16)
        for city in ["Tokyo", "Osaka", "Sapporo", "Fukuoka", "London", "New York"]:
            tk.Button(preset_frame, text=city, bg="#90caf9",
                      relief=tk.FLAT, font=("Arial", 9), padx=6,
                      command=lambda c=city: (self.city_var.set(c), self._search())
                      ).pack(side=tk.LEFT, padx=2, pady=4)

        # 現在の天気パネル
        self.current_frame = ttk.LabelFrame(self.root, text="現在の天気", padding=12)
        self.current_frame.pack(fill=tk.X, padx=16, pady=6)
        self.weather_icon_label = tk.Label(self.current_frame, text="",
                                           font=("Segoe UI Emoji", 40),
                                           bg=self.current_frame.cget("background"))
        self.weather_icon_label.grid(row=0, column=0, rowspan=3, padx=12)
        self.city_label = tk.Label(self.current_frame, text="---",
                                   font=("Noto Sans JP", 18, "bold"),
                                   bg=self.current_frame.cget("background"))
        self.city_label.grid(row=0, column=1, sticky="w")
        self.temp_label = tk.Label(self.current_frame, text="--°C",
                                   font=("Arial", 28, "bold"), fg="#1976d2",
                                   bg=self.current_frame.cget("background"))
        self.temp_label.grid(row=1, column=1, sticky="w")
        self.desc_label = tk.Label(self.current_frame, text="",
                                   font=("Noto Sans JP", 11),
                                   bg=self.current_frame.cget("background"))
        self.desc_label.grid(row=2, column=1, sticky="w")

        # 詳細情報
        detail_frame = tk.Frame(self.current_frame,
                                bg=self.current_frame.cget("background"))
        detail_frame.grid(row=0, column=2, rowspan=3, padx=20, sticky="n")
        self.detail_labels = {}
        for i, key in enumerate(["湿度", "風速", "体感温度", "気圧"]):
            tk.Label(detail_frame, text=f"{key}:", font=("Arial", 10),
                     bg=detail_frame.cget("bg")).grid(row=i, column=0, sticky="w", pady=2)
            lbl = tk.Label(detail_frame, text="--", font=("Arial", 10, "bold"),
                           bg=detail_frame.cget("bg"), fg="#1976d2")
            lbl.grid(row=i, column=1, sticky="w", padx=8)
            self.detail_labels[key] = lbl

        # 5日間予報
        forecast_frame = ttk.LabelFrame(self.root, text="5日間予報", padding=8)
        forecast_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 8))
        self.forecast_canvas = tk.Canvas(forecast_frame, bg="#f5f9ff",
                                         highlightthickness=0, height=160)
        self.forecast_canvas.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="都市名を入力して検索してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _search(self):
        city = self.city_var.get().strip()
        if not city:
            return
        self.status_var.set(f"取得中: {city} ...")
        threading.Thread(target=self._fetch_weather, args=(city,),
                         daemon=True).start()

    def _fetch_weather(self, city):
        try:
            # 現在天気
            url = (f"{self.BASE_URL}/weather?q={urllib.parse.quote(city)}"
                   f"&appid={self.API_KEY}&units=metric&lang=ja")
            with urllib.request.urlopen(url, timeout=10) as resp:
                data = json.loads(resp.read())
            self.root.after(0, self._update_current, data)

            # 5日間予報
            url5 = (f"{self.BASE_URL}/forecast?q={urllib.parse.quote(city)}"
                    f"&appid={self.API_KEY}&units=metric&lang=ja&cnt=40")
            with urllib.request.urlopen(url5, timeout=10) as resp:
                forecast = json.loads(resp.read())
            self.root.after(0, self._update_forecast, forecast)
        except urllib.error.HTTPError as e:
            if e.code == 401:
                msg = "APIキーが無効です。YOUR_API_KEY_HEREを実際のキーに置き換えてください"
            elif e.code == 404:
                msg = f"都市が見つかりません: {city}"
            else:
                msg = f"HTTPエラー: {e.code}"
            self.root.after(0, self._show_demo, city, msg)
        except Exception as e:
            self.root.after(0, self._show_demo, city, str(e))

    def _update_current(self, data):
        name = data["name"]
        temp = data["main"]["temp"]
        feels = data["main"]["feels_like"]
        hum = data["main"]["humidity"]
        wind = data["wind"]["speed"]
        pres = data["main"]["pressure"]
        desc = data["weather"][0]["description"]
        main = data["weather"][0]["main"]
        icon = self.WEATHER_ICONS.get(main, "🌡️")

        self.weather_icon_label.config(text=icon)
        self.city_label.config(text=name)
        self.temp_label.config(text=f"{temp:.1f}°C")
        self.desc_label.config(text=desc)
        self.detail_labels["湿度"].config(text=f"{hum}%")
        self.detail_labels["風速"].config(text=f"{wind} m/s")
        self.detail_labels["体感温度"].config(text=f"{feels:.1f}°C")
        self.detail_labels["気圧"].config(text=f"{pres} hPa")
        self.status_var.set(f"取得完了: {name}  ({datetime.now().strftime('%H:%M')})")

    def _update_forecast(self, data):
        self.forecast_canvas.delete("all")
        # 1日1エントリに集約(正午データ優先)
        days = {}
        for item in data["list"]:
            date = item["dt_txt"][:10]
            hour = item["dt_txt"][11:13]
            if date not in days or hour == "12":
                days[date] = item
        entries = list(days.values())[:5]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // max(len(entries), 1)
        for i, item in enumerate(entries):
            x = i * col_w + col_w // 2
            date = item["dt_txt"][:10]
            weekday = ["月", "火", "水", "木", "金", "土", "日"][
                datetime.strptime(date, "%Y-%m-%d").weekday()]
            temp = item["main"]["temp"]
            main = item["weather"][0]["main"]
            icon = self.WEATHER_ICONS.get(main, "🌡️")
            desc = item["weather"][0]["description"]

            self.forecast_canvas.create_text(x, 20, text=f"{date[5:]} ({weekday})",
                                             font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=f"{temp:.0f}°C",
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")
            if i < len(entries) - 1:
                self.forecast_canvas.create_line(
                    (i+1)*col_w, 10, (i+1)*col_w, 140, fill="#ccc")

    def _show_demo(self, city, error_msg):
        """APIキー未設定時はデモデータを表示"""
        self.weather_icon_label.config(text="☀️")
        self.city_label.config(text=f"{city} (デモ)")
        self.temp_label.config(text="22.5°C")
        self.desc_label.config(text="晴れ (デモデータ)")
        self.detail_labels["湿度"].config(text="55%")
        self.detail_labels["風速"].config(text="3.2 m/s")
        self.detail_labels["体感温度"].config(text="21.8°C")
        self.detail_labels["気圧"].config(text="1013 hPa")
        self.status_var.set(f"⚠ {error_msg}  ※デモ表示中")

        # デモ予報
        self.forecast_canvas.delete("all")
        demo = [("☀️", "22°C", "晴れ"), ("⛅", "19°C", "曇り"),
                ("🌧️", "16°C", "雨"), ("☁️", "18°C", "曇り"),
                ("☀️", "24°C", "晴れ")]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // 5
        from datetime import timedelta, date
        for i, (icon, temp, desc) in enumerate(demo):
            d = date.today() + timedelta(days=i)
            weekday = ["月", "火", "水", "木", "金", "土", "日"][d.weekday()]
            x = i * col_w + col_w // 2
            self.forecast_canvas.create_text(
                x, 20, text=f"{d.strftime('%m/%d')} ({weekday})", font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=temp,
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")


if __name__ == "__main__":
    root = tk.Tk()
    app = App04(root)
    root.mainloop()

例外処理とmessagebox

try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。

import tkinter as tk
from tkinter import ttk, messagebox
import json
import urllib.request
import urllib.error
import urllib.parse
import threading
from datetime import datetime


class App04:
    """天気予報アプリ"""

    # OpenWeatherMap API(無料枠)
    API_KEY = "YOUR_API_KEY_HERE"
    BASE_URL = "https://api.openweathermap.org/data/2.5"

    WEATHER_ICONS = {
        "Clear": "☀️", "Clouds": "☁️", "Rain": "🌧️",
        "Drizzle": "🌦️", "Thunderstorm": "⛈️", "Snow": "❄️",
        "Mist": "🌫️", "Fog": "🌫️", "Haze": "🌫️",
    }

    def __init__(self, root):
        self.root = root
        self.root.title("天気予報アプリ")
        self.root.geometry("600x540")
        self.root.configure(bg="#e8f4fd")
        self._build_ui()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#1976d2", pady=10)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="🌤️ 天気予報アプリ",
                 font=("Noto Sans JP", 15, "bold"),
                 bg="#1976d2", fg="white").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#e8f4fd", pady=10)
        search_frame.pack(fill=tk.X, padx=16)
        tk.Label(search_frame, text="都市名 (英語):",
                 bg="#e8f4fd", font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.city_var = tk.StringVar(value="Tokyo")
        city_entry = ttk.Entry(search_frame, textvariable=self.city_var,
                               font=("Arial", 12), width=20)
        city_entry.pack(side=tk.LEFT, padx=8)
        city_entry.bind("<Return>", lambda e: self._search())
        ttk.Button(search_frame, text="🔍 検索",
                   command=self._search).pack(side=tk.LEFT)

        # プリセット都市ボタン
        preset_frame = tk.Frame(self.root, bg="#e8f4fd")
        preset_frame.pack(fill=tk.X, padx=16)
        for city in ["Tokyo", "Osaka", "Sapporo", "Fukuoka", "London", "New York"]:
            tk.Button(preset_frame, text=city, bg="#90caf9",
                      relief=tk.FLAT, font=("Arial", 9), padx=6,
                      command=lambda c=city: (self.city_var.set(c), self._search())
                      ).pack(side=tk.LEFT, padx=2, pady=4)

        # 現在の天気パネル
        self.current_frame = ttk.LabelFrame(self.root, text="現在の天気", padding=12)
        self.current_frame.pack(fill=tk.X, padx=16, pady=6)
        self.weather_icon_label = tk.Label(self.current_frame, text="",
                                           font=("Segoe UI Emoji", 40),
                                           bg=self.current_frame.cget("background"))
        self.weather_icon_label.grid(row=0, column=0, rowspan=3, padx=12)
        self.city_label = tk.Label(self.current_frame, text="---",
                                   font=("Noto Sans JP", 18, "bold"),
                                   bg=self.current_frame.cget("background"))
        self.city_label.grid(row=0, column=1, sticky="w")
        self.temp_label = tk.Label(self.current_frame, text="--°C",
                                   font=("Arial", 28, "bold"), fg="#1976d2",
                                   bg=self.current_frame.cget("background"))
        self.temp_label.grid(row=1, column=1, sticky="w")
        self.desc_label = tk.Label(self.current_frame, text="",
                                   font=("Noto Sans JP", 11),
                                   bg=self.current_frame.cget("background"))
        self.desc_label.grid(row=2, column=1, sticky="w")

        # 詳細情報
        detail_frame = tk.Frame(self.current_frame,
                                bg=self.current_frame.cget("background"))
        detail_frame.grid(row=0, column=2, rowspan=3, padx=20, sticky="n")
        self.detail_labels = {}
        for i, key in enumerate(["湿度", "風速", "体感温度", "気圧"]):
            tk.Label(detail_frame, text=f"{key}:", font=("Arial", 10),
                     bg=detail_frame.cget("bg")).grid(row=i, column=0, sticky="w", pady=2)
            lbl = tk.Label(detail_frame, text="--", font=("Arial", 10, "bold"),
                           bg=detail_frame.cget("bg"), fg="#1976d2")
            lbl.grid(row=i, column=1, sticky="w", padx=8)
            self.detail_labels[key] = lbl

        # 5日間予報
        forecast_frame = ttk.LabelFrame(self.root, text="5日間予報", padding=8)
        forecast_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 8))
        self.forecast_canvas = tk.Canvas(forecast_frame, bg="#f5f9ff",
                                         highlightthickness=0, height=160)
        self.forecast_canvas.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="都市名を入力して検索してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#dde", font=("Arial", 9), anchor="w", padx=8
                 ).pack(fill=tk.X, side=tk.BOTTOM)

    def _search(self):
        city = self.city_var.get().strip()
        if not city:
            return
        self.status_var.set(f"取得中: {city} ...")
        threading.Thread(target=self._fetch_weather, args=(city,),
                         daemon=True).start()

    def _fetch_weather(self, city):
        try:
            # 現在天気
            url = (f"{self.BASE_URL}/weather?q={urllib.parse.quote(city)}"
                   f"&appid={self.API_KEY}&units=metric&lang=ja")
            with urllib.request.urlopen(url, timeout=10) as resp:
                data = json.loads(resp.read())
            self.root.after(0, self._update_current, data)

            # 5日間予報
            url5 = (f"{self.BASE_URL}/forecast?q={urllib.parse.quote(city)}"
                    f"&appid={self.API_KEY}&units=metric&lang=ja&cnt=40")
            with urllib.request.urlopen(url5, timeout=10) as resp:
                forecast = json.loads(resp.read())
            self.root.after(0, self._update_forecast, forecast)
        except urllib.error.HTTPError as e:
            if e.code == 401:
                msg = "APIキーが無効です。YOUR_API_KEY_HEREを実際のキーに置き換えてください"
            elif e.code == 404:
                msg = f"都市が見つかりません: {city}"
            else:
                msg = f"HTTPエラー: {e.code}"
            self.root.after(0, self._show_demo, city, msg)
        except Exception as e:
            self.root.after(0, self._show_demo, city, str(e))

    def _update_current(self, data):
        name = data["name"]
        temp = data["main"]["temp"]
        feels = data["main"]["feels_like"]
        hum = data["main"]["humidity"]
        wind = data["wind"]["speed"]
        pres = data["main"]["pressure"]
        desc = data["weather"][0]["description"]
        main = data["weather"][0]["main"]
        icon = self.WEATHER_ICONS.get(main, "🌡️")

        self.weather_icon_label.config(text=icon)
        self.city_label.config(text=name)
        self.temp_label.config(text=f"{temp:.1f}°C")
        self.desc_label.config(text=desc)
        self.detail_labels["湿度"].config(text=f"{hum}%")
        self.detail_labels["風速"].config(text=f"{wind} m/s")
        self.detail_labels["体感温度"].config(text=f"{feels:.1f}°C")
        self.detail_labels["気圧"].config(text=f"{pres} hPa")
        self.status_var.set(f"取得完了: {name}  ({datetime.now().strftime('%H:%M')})")

    def _update_forecast(self, data):
        self.forecast_canvas.delete("all")
        # 1日1エントリに集約(正午データ優先)
        days = {}
        for item in data["list"]:
            date = item["dt_txt"][:10]
            hour = item["dt_txt"][11:13]
            if date not in days or hour == "12":
                days[date] = item
        entries = list(days.values())[:5]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // max(len(entries), 1)
        for i, item in enumerate(entries):
            x = i * col_w + col_w // 2
            date = item["dt_txt"][:10]
            weekday = ["月", "火", "水", "木", "金", "土", "日"][
                datetime.strptime(date, "%Y-%m-%d").weekday()]
            temp = item["main"]["temp"]
            main = item["weather"][0]["main"]
            icon = self.WEATHER_ICONS.get(main, "🌡️")
            desc = item["weather"][0]["description"]

            self.forecast_canvas.create_text(x, 20, text=f"{date[5:]} ({weekday})",
                                             font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=f"{temp:.0f}°C",
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")
            if i < len(entries) - 1:
                self.forecast_canvas.create_line(
                    (i+1)*col_w, 10, (i+1)*col_w, 140, fill="#ccc")

    def _show_demo(self, city, error_msg):
        """APIキー未設定時はデモデータを表示"""
        self.weather_icon_label.config(text="☀️")
        self.city_label.config(text=f"{city} (デモ)")
        self.temp_label.config(text="22.5°C")
        self.desc_label.config(text="晴れ (デモデータ)")
        self.detail_labels["湿度"].config(text="55%")
        self.detail_labels["風速"].config(text="3.2 m/s")
        self.detail_labels["体感温度"].config(text="21.8°C")
        self.detail_labels["気圧"].config(text="1013 hPa")
        self.status_var.set(f"⚠ {error_msg}  ※デモ表示中")

        # デモ予報
        self.forecast_canvas.delete("all")
        demo = [("☀️", "22°C", "晴れ"), ("⛅", "19°C", "曇り"),
                ("🌧️", "16°C", "雨"), ("☁️", "18°C", "曇り"),
                ("☀️", "24°C", "晴れ")]
        w = self.forecast_canvas.winfo_width() or 560
        col_w = w // 5
        from datetime import timedelta, date
        for i, (icon, temp, desc) in enumerate(demo):
            d = date.today() + timedelta(days=i)
            weekday = ["月", "火", "水", "木", "金", "土", "日"][d.weekday()]
            x = i * col_w + col_w // 2
            self.forecast_canvas.create_text(
                x, 20, text=f"{d.strftime('%m/%d')} ({weekday})", font=("Arial", 9))
            self.forecast_canvas.create_text(x, 50, text=icon,
                                             font=("Segoe UI Emoji", 22))
            self.forecast_canvas.create_text(x, 90, text=temp,
                                             font=("Arial", 13, "bold"), fill="#1976d2")
            self.forecast_canvas.create_text(x, 115, text=desc,
                                             font=("Arial", 8), fill="#555")


if __name__ == "__main__":
    root = tk.Tk()
    app = App04(root)
    root.mainloop()

6. ステップバイステップガイド

このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。

  1. 1
    ファイルを作成する

    新しいファイルを作成して app04.py と保存します。

  2. 2
    クラスの骨格を作る

    App04クラスを定義し、__init__とmainloop()の最小構成を作ります。

  3. 3
    タイトルバーを作る

    Frameを使ってカラーバー付きのタイトルエリアを作ります。

  4. 4
    入力フォームを実装する

    LabelFrameとEntryウィジェットで入力エリアを作ります。

  5. 5
    処理ロジックを実装する

    _calculate()メソッドに計算・処理ロジックを実装します。

  6. 6
    結果表示を実装する

    TextウィジェットかLabelに結果を表示する_show_result()を実装します。

  7. 7
    エラー処理を追加する

    try-exceptとmessageboxでエラーハンドリングを追加します。

7. カスタマイズアイデア

基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。少しずつ機能を追加することで、Pythonのスキルが飛躍的に向上します。

💡 ダークモードを追加する

bg色・fg色を辞書で管理し、ボタン1つでダークモード・ライトモードを切り替えられるようにしましょう。

💡 データのエクスポート機能

計算結果をCSV・TXTファイルに保存するエクスポート機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。

💡 入力履歴機能

以前の入力値を覚えておいてComboboxのドロップダウンで再選択できる履歴機能を追加しましょう。

8. よくある問題と解決法

❌ 日本語フォントが表示されない

原因:システムに日本語フォントが見つからない場合があります。

解決法:font引数を省略するかシステムに合ったフォントを指定してください。

❌ ウィンドウのサイズが変更できない

原因:resizable(False, False)が設定されています。

解決法:resizable(True, True)に変更してください。

9. 練習問題

アプリの理解を深めるための練習問題です。難易度順に挑戦してみてください。

  1. 課題1:機能拡張

    天気予報アプリに新しい機能を1つ追加してみましょう。どんな機能があると便利か考えてから実装してください。

  2. 課題2:UIの改善

    色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしてみましょう。

  3. 課題3:保存機能の追加

    入力値や計算結果をファイルに保存する機能を追加しましょう。jsonやcsvモジュールを使います。

🚀
次に挑戦するアプリ

このアプリをマスターしたら、次のNo.05に挑戦しましょう。