初心者向け No.18

カレンダー表示アプリ

月のカレンダーをグリッド表示し前後月へ移動できるアプリ。calendarモジュールの活用方法を学びます。

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

1. アプリ概要

月のカレンダーをグリッド表示し前後月へ移動できるアプリ。calendarモジュールの活用方法を学びます。

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

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. 完全なソースコード

💡
コードのコピー方法

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

app18.py
import tkinter as tk
from tkinter import ttk
import calendar
from datetime import date


class App18:
    """カレンダー表示アプリ"""

    def __init__(self, root):
        self.root = root
        self.root.title("カレンダー表示アプリ")
        self.root.geometry("420x360")
        self.root.configure(bg="#f8f9fc")
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._build_ui()
        self._draw_calendar()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="カレンダー",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        nav_frame = tk.Frame(self.root, bg="#f8f9fc", pady=8)
        nav_frame.pack(fill=tk.X, padx=16)

        ttk.Button(nav_frame, text="◀", width=3, command=self.prev_month).pack(side=tk.LEFT)
        self.month_label = tk.Label(nav_frame, text="", font=("Noto Sans JP", 14, "bold"),
                                    bg="#f8f9fc", width=16, anchor="center")
        self.month_label.pack(side=tk.LEFT, expand=True)
        ttk.Button(nav_frame, text="▶", width=3, command=self.next_month).pack(side=tk.RIGHT)
        ttk.Button(nav_frame, text="今月", width=5, command=self.goto_today).pack(side=tk.RIGHT, padx=4)

        self.cal_frame = tk.Frame(self.root, bg="#f8f9fc")
        self.cal_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 12))

    def _draw_calendar(self):
        for w in self.cal_frame.winfo_children():
            w.destroy()

        self.month_label.config(text=f"{self.year}年 {self.month}月")

        cal = calendar.monthcalendar(self.year, self.month)
        today = date.today()

        headers = ["月", "火", "水", "木", "金", "土", "日"]
        for col, h in enumerate(headers):
            color = "#e74c3c" if h == "日" else "#3776ab" if h == "土" else "#555"
            tk.Label(self.cal_frame, text=h, font=("Noto Sans JP", 11, "bold"),
                     bg="#f8f9fc", fg=color, width=4).grid(row=0, column=col, pady=(0, 4))

        for row, week in enumerate(cal):
            for col, day in enumerate(week):
                if day == 0:
                    tk.Label(self.cal_frame, text="", bg="#f8f9fc", width=4).grid(
                        row=row + 1, column=col)
                    continue
                is_today = (day == today.day and self.month == today.month
                            and self.year == today.year)
                fg = "#e74c3c" if col == 6 else "#3776ab" if col == 5 else "#222"
                bg = "#3776ab" if is_today else "#f8f9fc"
                text_fg = "white" if is_today else fg
                lbl = tk.Label(self.cal_frame, text=str(day),
                               font=("Noto Sans JP", 11, "bold" if is_today else "normal"),
                               bg=bg, fg=text_fg, width=4, relief="flat",
                               padx=2, pady=2)
                lbl.grid(row=row + 1, column=col, padx=1, pady=1)

    def prev_month(self):
        if self.month == 1:
            self.month = 12
            self.year -= 1
        else:
            self.month -= 1
        self._draw_calendar()

    def next_month(self):
        if self.month == 12:
            self.month = 1
            self.year += 1
        else:
            self.month += 1
        self._draw_calendar()

    def goto_today(self):
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._draw_calendar()


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

5. コード解説

カレンダー表示アプリのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

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

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

import tkinter as tk
from tkinter import ttk
import calendar
from datetime import date


class App18:
    """カレンダー表示アプリ"""

    def __init__(self, root):
        self.root = root
        self.root.title("カレンダー表示アプリ")
        self.root.geometry("420x360")
        self.root.configure(bg="#f8f9fc")
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._build_ui()
        self._draw_calendar()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="カレンダー",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        nav_frame = tk.Frame(self.root, bg="#f8f9fc", pady=8)
        nav_frame.pack(fill=tk.X, padx=16)

        ttk.Button(nav_frame, text="◀", width=3, command=self.prev_month).pack(side=tk.LEFT)
        self.month_label = tk.Label(nav_frame, text="", font=("Noto Sans JP", 14, "bold"),
                                    bg="#f8f9fc", width=16, anchor="center")
        self.month_label.pack(side=tk.LEFT, expand=True)
        ttk.Button(nav_frame, text="▶", width=3, command=self.next_month).pack(side=tk.RIGHT)
        ttk.Button(nav_frame, text="今月", width=5, command=self.goto_today).pack(side=tk.RIGHT, padx=4)

        self.cal_frame = tk.Frame(self.root, bg="#f8f9fc")
        self.cal_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 12))

    def _draw_calendar(self):
        for w in self.cal_frame.winfo_children():
            w.destroy()

        self.month_label.config(text=f"{self.year}年 {self.month}月")

        cal = calendar.monthcalendar(self.year, self.month)
        today = date.today()

        headers = ["月", "火", "水", "木", "金", "土", "日"]
        for col, h in enumerate(headers):
            color = "#e74c3c" if h == "日" else "#3776ab" if h == "土" else "#555"
            tk.Label(self.cal_frame, text=h, font=("Noto Sans JP", 11, "bold"),
                     bg="#f8f9fc", fg=color, width=4).grid(row=0, column=col, pady=(0, 4))

        for row, week in enumerate(cal):
            for col, day in enumerate(week):
                if day == 0:
                    tk.Label(self.cal_frame, text="", bg="#f8f9fc", width=4).grid(
                        row=row + 1, column=col)
                    continue
                is_today = (day == today.day and self.month == today.month
                            and self.year == today.year)
                fg = "#e74c3c" if col == 6 else "#3776ab" if col == 5 else "#222"
                bg = "#3776ab" if is_today else "#f8f9fc"
                text_fg = "white" if is_today else fg
                lbl = tk.Label(self.cal_frame, text=str(day),
                               font=("Noto Sans JP", 11, "bold" if is_today else "normal"),
                               bg=bg, fg=text_fg, width=4, relief="flat",
                               padx=2, pady=2)
                lbl.grid(row=row + 1, column=col, padx=1, pady=1)

    def prev_month(self):
        if self.month == 1:
            self.month = 12
            self.year -= 1
        else:
            self.month -= 1
        self._draw_calendar()

    def next_month(self):
        if self.month == 12:
            self.month = 1
            self.year += 1
        else:
            self.month += 1
        self._draw_calendar()

    def goto_today(self):
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._draw_calendar()


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

LabelFrameによるセクション分け

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

import tkinter as tk
from tkinter import ttk
import calendar
from datetime import date


class App18:
    """カレンダー表示アプリ"""

    def __init__(self, root):
        self.root = root
        self.root.title("カレンダー表示アプリ")
        self.root.geometry("420x360")
        self.root.configure(bg="#f8f9fc")
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._build_ui()
        self._draw_calendar()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="カレンダー",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        nav_frame = tk.Frame(self.root, bg="#f8f9fc", pady=8)
        nav_frame.pack(fill=tk.X, padx=16)

        ttk.Button(nav_frame, text="◀", width=3, command=self.prev_month).pack(side=tk.LEFT)
        self.month_label = tk.Label(nav_frame, text="", font=("Noto Sans JP", 14, "bold"),
                                    bg="#f8f9fc", width=16, anchor="center")
        self.month_label.pack(side=tk.LEFT, expand=True)
        ttk.Button(nav_frame, text="▶", width=3, command=self.next_month).pack(side=tk.RIGHT)
        ttk.Button(nav_frame, text="今月", width=5, command=self.goto_today).pack(side=tk.RIGHT, padx=4)

        self.cal_frame = tk.Frame(self.root, bg="#f8f9fc")
        self.cal_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 12))

    def _draw_calendar(self):
        for w in self.cal_frame.winfo_children():
            w.destroy()

        self.month_label.config(text=f"{self.year}年 {self.month}月")

        cal = calendar.monthcalendar(self.year, self.month)
        today = date.today()

        headers = ["月", "火", "水", "木", "金", "土", "日"]
        for col, h in enumerate(headers):
            color = "#e74c3c" if h == "日" else "#3776ab" if h == "土" else "#555"
            tk.Label(self.cal_frame, text=h, font=("Noto Sans JP", 11, "bold"),
                     bg="#f8f9fc", fg=color, width=4).grid(row=0, column=col, pady=(0, 4))

        for row, week in enumerate(cal):
            for col, day in enumerate(week):
                if day == 0:
                    tk.Label(self.cal_frame, text="", bg="#f8f9fc", width=4).grid(
                        row=row + 1, column=col)
                    continue
                is_today = (day == today.day and self.month == today.month
                            and self.year == today.year)
                fg = "#e74c3c" if col == 6 else "#3776ab" if col == 5 else "#222"
                bg = "#3776ab" if is_today else "#f8f9fc"
                text_fg = "white" if is_today else fg
                lbl = tk.Label(self.cal_frame, text=str(day),
                               font=("Noto Sans JP", 11, "bold" if is_today else "normal"),
                               bg=bg, fg=text_fg, width=4, relief="flat",
                               padx=2, pady=2)
                lbl.grid(row=row + 1, column=col, padx=1, pady=1)

    def prev_month(self):
        if self.month == 1:
            self.month = 12
            self.year -= 1
        else:
            self.month -= 1
        self._draw_calendar()

    def next_month(self):
        if self.month == 12:
            self.month = 1
            self.year += 1
        else:
            self.month += 1
        self._draw_calendar()

    def goto_today(self):
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._draw_calendar()


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

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

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

import tkinter as tk
from tkinter import ttk
import calendar
from datetime import date


class App18:
    """カレンダー表示アプリ"""

    def __init__(self, root):
        self.root = root
        self.root.title("カレンダー表示アプリ")
        self.root.geometry("420x360")
        self.root.configure(bg="#f8f9fc")
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._build_ui()
        self._draw_calendar()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="カレンダー",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        nav_frame = tk.Frame(self.root, bg="#f8f9fc", pady=8)
        nav_frame.pack(fill=tk.X, padx=16)

        ttk.Button(nav_frame, text="◀", width=3, command=self.prev_month).pack(side=tk.LEFT)
        self.month_label = tk.Label(nav_frame, text="", font=("Noto Sans JP", 14, "bold"),
                                    bg="#f8f9fc", width=16, anchor="center")
        self.month_label.pack(side=tk.LEFT, expand=True)
        ttk.Button(nav_frame, text="▶", width=3, command=self.next_month).pack(side=tk.RIGHT)
        ttk.Button(nav_frame, text="今月", width=5, command=self.goto_today).pack(side=tk.RIGHT, padx=4)

        self.cal_frame = tk.Frame(self.root, bg="#f8f9fc")
        self.cal_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 12))

    def _draw_calendar(self):
        for w in self.cal_frame.winfo_children():
            w.destroy()

        self.month_label.config(text=f"{self.year}年 {self.month}月")

        cal = calendar.monthcalendar(self.year, self.month)
        today = date.today()

        headers = ["月", "火", "水", "木", "金", "土", "日"]
        for col, h in enumerate(headers):
            color = "#e74c3c" if h == "日" else "#3776ab" if h == "土" else "#555"
            tk.Label(self.cal_frame, text=h, font=("Noto Sans JP", 11, "bold"),
                     bg="#f8f9fc", fg=color, width=4).grid(row=0, column=col, pady=(0, 4))

        for row, week in enumerate(cal):
            for col, day in enumerate(week):
                if day == 0:
                    tk.Label(self.cal_frame, text="", bg="#f8f9fc", width=4).grid(
                        row=row + 1, column=col)
                    continue
                is_today = (day == today.day and self.month == today.month
                            and self.year == today.year)
                fg = "#e74c3c" if col == 6 else "#3776ab" if col == 5 else "#222"
                bg = "#3776ab" if is_today else "#f8f9fc"
                text_fg = "white" if is_today else fg
                lbl = tk.Label(self.cal_frame, text=str(day),
                               font=("Noto Sans JP", 11, "bold" if is_today else "normal"),
                               bg=bg, fg=text_fg, width=4, relief="flat",
                               padx=2, pady=2)
                lbl.grid(row=row + 1, column=col, padx=1, pady=1)

    def prev_month(self):
        if self.month == 1:
            self.month = 12
            self.year -= 1
        else:
            self.month -= 1
        self._draw_calendar()

    def next_month(self):
        if self.month == 12:
            self.month = 1
            self.year += 1
        else:
            self.month += 1
        self._draw_calendar()

    def goto_today(self):
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._draw_calendar()


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

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

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

import tkinter as tk
from tkinter import ttk
import calendar
from datetime import date


class App18:
    """カレンダー表示アプリ"""

    def __init__(self, root):
        self.root = root
        self.root.title("カレンダー表示アプリ")
        self.root.geometry("420x360")
        self.root.configure(bg="#f8f9fc")
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._build_ui()
        self._draw_calendar()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="カレンダー",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        nav_frame = tk.Frame(self.root, bg="#f8f9fc", pady=8)
        nav_frame.pack(fill=tk.X, padx=16)

        ttk.Button(nav_frame, text="◀", width=3, command=self.prev_month).pack(side=tk.LEFT)
        self.month_label = tk.Label(nav_frame, text="", font=("Noto Sans JP", 14, "bold"),
                                    bg="#f8f9fc", width=16, anchor="center")
        self.month_label.pack(side=tk.LEFT, expand=True)
        ttk.Button(nav_frame, text="▶", width=3, command=self.next_month).pack(side=tk.RIGHT)
        ttk.Button(nav_frame, text="今月", width=5, command=self.goto_today).pack(side=tk.RIGHT, padx=4)

        self.cal_frame = tk.Frame(self.root, bg="#f8f9fc")
        self.cal_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 12))

    def _draw_calendar(self):
        for w in self.cal_frame.winfo_children():
            w.destroy()

        self.month_label.config(text=f"{self.year}年 {self.month}月")

        cal = calendar.monthcalendar(self.year, self.month)
        today = date.today()

        headers = ["月", "火", "水", "木", "金", "土", "日"]
        for col, h in enumerate(headers):
            color = "#e74c3c" if h == "日" else "#3776ab" if h == "土" else "#555"
            tk.Label(self.cal_frame, text=h, font=("Noto Sans JP", 11, "bold"),
                     bg="#f8f9fc", fg=color, width=4).grid(row=0, column=col, pady=(0, 4))

        for row, week in enumerate(cal):
            for col, day in enumerate(week):
                if day == 0:
                    tk.Label(self.cal_frame, text="", bg="#f8f9fc", width=4).grid(
                        row=row + 1, column=col)
                    continue
                is_today = (day == today.day and self.month == today.month
                            and self.year == today.year)
                fg = "#e74c3c" if col == 6 else "#3776ab" if col == 5 else "#222"
                bg = "#3776ab" if is_today else "#f8f9fc"
                text_fg = "white" if is_today else fg
                lbl = tk.Label(self.cal_frame, text=str(day),
                               font=("Noto Sans JP", 11, "bold" if is_today else "normal"),
                               bg=bg, fg=text_fg, width=4, relief="flat",
                               padx=2, pady=2)
                lbl.grid(row=row + 1, column=col, padx=1, pady=1)

    def prev_month(self):
        if self.month == 1:
            self.month = 12
            self.year -= 1
        else:
            self.month -= 1
        self._draw_calendar()

    def next_month(self):
        if self.month == 12:
            self.month = 1
            self.year += 1
        else:
            self.month += 1
        self._draw_calendar()

    def goto_today(self):
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._draw_calendar()


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

例外処理とmessagebox

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

import tkinter as tk
from tkinter import ttk
import calendar
from datetime import date


class App18:
    """カレンダー表示アプリ"""

    def __init__(self, root):
        self.root = root
        self.root.title("カレンダー表示アプリ")
        self.root.geometry("420x360")
        self.root.configure(bg="#f8f9fc")
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._build_ui()
        self._draw_calendar()

    def _build_ui(self):
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(title_frame, text="カレンダー",
                 font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        nav_frame = tk.Frame(self.root, bg="#f8f9fc", pady=8)
        nav_frame.pack(fill=tk.X, padx=16)

        ttk.Button(nav_frame, text="◀", width=3, command=self.prev_month).pack(side=tk.LEFT)
        self.month_label = tk.Label(nav_frame, text="", font=("Noto Sans JP", 14, "bold"),
                                    bg="#f8f9fc", width=16, anchor="center")
        self.month_label.pack(side=tk.LEFT, expand=True)
        ttk.Button(nav_frame, text="▶", width=3, command=self.next_month).pack(side=tk.RIGHT)
        ttk.Button(nav_frame, text="今月", width=5, command=self.goto_today).pack(side=tk.RIGHT, padx=4)

        self.cal_frame = tk.Frame(self.root, bg="#f8f9fc")
        self.cal_frame.pack(fill=tk.BOTH, expand=True, padx=16, pady=(0, 12))

    def _draw_calendar(self):
        for w in self.cal_frame.winfo_children():
            w.destroy()

        self.month_label.config(text=f"{self.year}年 {self.month}月")

        cal = calendar.monthcalendar(self.year, self.month)
        today = date.today()

        headers = ["月", "火", "水", "木", "金", "土", "日"]
        for col, h in enumerate(headers):
            color = "#e74c3c" if h == "日" else "#3776ab" if h == "土" else "#555"
            tk.Label(self.cal_frame, text=h, font=("Noto Sans JP", 11, "bold"),
                     bg="#f8f9fc", fg=color, width=4).grid(row=0, column=col, pady=(0, 4))

        for row, week in enumerate(cal):
            for col, day in enumerate(week):
                if day == 0:
                    tk.Label(self.cal_frame, text="", bg="#f8f9fc", width=4).grid(
                        row=row + 1, column=col)
                    continue
                is_today = (day == today.day and self.month == today.month
                            and self.year == today.year)
                fg = "#e74c3c" if col == 6 else "#3776ab" if col == 5 else "#222"
                bg = "#3776ab" if is_today else "#f8f9fc"
                text_fg = "white" if is_today else fg
                lbl = tk.Label(self.cal_frame, text=str(day),
                               font=("Noto Sans JP", 11, "bold" if is_today else "normal"),
                               bg=bg, fg=text_fg, width=4, relief="flat",
                               padx=2, pady=2)
                lbl.grid(row=row + 1, column=col, padx=1, pady=1)

    def prev_month(self):
        if self.month == 1:
            self.month = 12
            self.year -= 1
        else:
            self.month -= 1
        self._draw_calendar()

    def next_month(self):
        if self.month == 12:
            self.month = 1
            self.year += 1
        else:
            self.month += 1
        self._draw_calendar()

    def goto_today(self):
        today = date.today()
        self.year = today.year
        self.month = today.month
        self._draw_calendar()


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

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

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

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

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

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

    App18クラスを定義し、__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.19に挑戦しましょう。