Kazuki's Blog

ITは活用する道具である!

tkinterを利用してカレンダーWidgetと予定・実績管理Widgetを統合する(その5: カレンダーの月移動機能の実装とレイアウトの最適化)

はじめに

前回までは、PanedWindow を利用したアプリケーションの全体的なレイアウト構造の構築と、祝日判定ライブラリ jpholiday を組み込んだカレンダーの基本表示までを実装してきました。 今回は、デスクトップアプリとしての実用性を高めるための大きな一歩として、「カレンダーの月移動(前月・翌月)機能」の実装と、カレンダーセルのレイアウト崩れを防ぐための「サイズ固定化」の対応を行いました。UIの操作性と視覚的な安定性を向上させた更新内容を解説します。

1. 今回の主な更新内容

今回は、主に以下の3点について改善を行いました。

1. カレンダーの月移動ロジックの実装

これまではボタンがあるだけだった「前月」「次月」ボタンに、実際の切り替え処理を実装しました。 _previous_month および _next_month メソッドにおいて、月が1月や12月をまたぐ際の年繰り上げ・繰り下げ処理を行い、更新後に _display_calendar() を再呼出することで、動的な表示切り替えを可能にしています。

def _previous_month(self):
    """カレンダーを前月に切り替えます。"""
    if self.current_month == 1:
        self.current_month = 12
        self.current_year -= 1
    else:
        self.current_month -= 1
    self._display_calendar()

2. セルサイズの固定とレイアウトの安定化

これまでは Label ウィジェットを直接配置していましたが、今回は各日付の土台として Frame を導入しました。 ポイントは、grid_propagate(False) を使用して、中身のテキスト(祝日名など)の長さに左右されず、セルの高さと幅を一定に保つようにした点です。これにより、情報の多い日があってもカレンダー全体のグリッドがガタつくことがなくなりました。

3. 祝日表示の最適化

祝日名が長い場合に枠からはみ出してしまう問題を解決するため、祝日名の文字数に応じてフォントサイズを動的に変更するロジックを追加しました。 また、wraplength を設定することで、枠幅に合わせた自動改行も行っています。

# 祝日名の長さに応じてフォントサイズを調整
h_font_size = 7 if len(self.holiday_name) > 5 else 8
holiday_label = tk.Label(
    ...
    wraplength=80 # 枠の幅に合わせて自動改行
)

3. その他の対応

カレンダーの表示更新時には、self.calendar_frame.winfo_children() をループで回して既存のウィジェットをすべて destroy() してから再描画しています。これにより、メモリリークを防ぎつつ、常に最新の状態をクリーンに表示できるようになっています。

また、色の指定をより洗練させ、日曜・祝日は #e60000(赤)、土曜日は #0099ff(青)といった、よりデスクトップアプリらしい配色に微調整しました。

2. Pythonスクリプト

"""
カレンダー、メモ、スケジュール機能を備えたデスクトップアプリケーションのモジュール。
TkinterのPanedWindowをネストしてレイアウトを構築します。
"""

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


# 定数管理
APP_NAME = "カレンダーアプリ - カレンダー・メモ・スケジュール機能"
WIN_SIZE = "1200x800"


class CalendarMemoScheduleApp:
    # 属性数が多いのはGUIクラスの特性であるため、Pylintの警告を抑制
    # pylint: disable=too-many-instance-attributes
    """
    アプリケーションのメインウィンドウとUIコンポーネントを管理するクラス。
    """

    def __init__(self, root):
        """
        初期化メソッド。
        :param root: Tkinterのルートウィンドウインスタンス
        """
        self.root = root
        self.root.title(APP_NAME)
        self.root.geometry(WIN_SIZE)

        # インスタンス属性の初期化 (W0201対策)
        self.pw_horizontal = None
        self.pw_vertical_left = None
        self.calendar_container = None
        self.calendar_header_frame = None
        self.calendar_prev_button = None
        self.calendar_month_label = None
        self.calendar_next_button = None
        self.calendar_frame = None
        self.label_left_bottom = None
        self.label_right = None
        self.note_container = None
        self.note_header_frame = None
        self.note_date_label = None
        self.note_button_container = None
        self.note_save_button = None
        self.holiday_name = None

        # 現在の年月を初期値として設定
        self.current_year = datetime.now().year
        self.current_month = datetime.now().month
        self.selected_date = datetime.now().date()

        # 内部用UI構築メソッドの呼び出し
        self._setup_ui()

    def _setup_ui(self):
        """
        メインのUIレイアウトを設定
        """
        self._create_paned_widgets()

    def _create_paned_widgets(self):
        """
        PanedWindowを生成し、各ペインにウィジェットを追加します。
        """
        # 1. 一番外側のPanedWindow(左右分割)
        self.pw_horizontal = ttk.Panedwindow(self.root, orient=tk.HORIZONTAL)
        self.pw_horizontal.pack(fill=tk.BOTH, expand=True)

        # --- 左側のエリア ---
        self._setup_left_area()

        # --- 右側のエリア ---
        self._setup_right_area()

    def _setup_left_area(self):
        """
        左側のペイン(カレンダーとメモ)を構築します。
        """
        # 左ペインの中に「上下分割」のPanedWindowを作成
        self.pw_vertical_left = ttk.Panedwindow(self.pw_horizontal, orient=tk.VERTICAL)
        self.pw_horizontal.add(self.pw_vertical_left, weight=1)

        # カレンダー部分の構築
        self._create_calendar_section()

        # メモエリアの構築
        self._create_memo_section()

    def _create_calendar_section(self):
        """
        左ペイン上部のカレンダーセクション(ヘッダーとフレーム)を生成します。
        """
        # カレンダー全体のコンテナ
        self.calendar_container = tk.Frame(self.pw_vertical_left)
        self.pw_vertical_left.add(self.calendar_container, weight=1)

        # ヘッダー(月移動ナビゲーション)
        self.calendar_header_frame = tk.Frame(self.calendar_container, bg="#040353", pady=5)
        self.calendar_header_frame.pack(fill=tk.X)

        # 前月ボタン
        self.calendar_prev_button = tk.Button(
            self.calendar_header_frame, text="< 前月", command=self._previous_month,
            font=("Arial", 10), width=5
        )
        self.calendar_prev_button.pack(side=tk.LEFT, padx=20)

        # 年月表示ラベル
        self.calendar_month_label = tk.Label(
            self.calendar_header_frame, text="xxxx年x月", font=("Arial", 10, "bold")
        )
        self.calendar_month_label.pack(side=tk.LEFT, expand=True)

        # 次月ボタン
        self.calendar_next_button = tk.Button(
            self.calendar_header_frame, text="次月 >", command=self._next_month,
            font=("Arial", 10), width=5
        )
        self.calendar_next_button.pack(side=tk.RIGHT, padx=20)

        # カレンダーの日付グリッド表示エリア
        self.calendar_frame = tk.Frame(self.calendar_container, bg="white")
        self.calendar_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # カレンダーの表示
        self._display_calendar()

    def _previous_month(self):
        """カレンダーを前月に切り替えます。"""
        if self.current_month == 1:
            self.current_month = 12
            self.current_year -= 1
        else:
            self.current_month -= 1
        self._display_calendar()

    def _next_month(self):
        """カレンダーを翌月に切り替えます。"""
        if self.current_month == 12:
            self.current_month = 1
            self.current_year += 1
        else:
            self.current_month += 1
        self._display_calendar()

    def _display_calendar(self):
        """カレンダーを表示します。"""
        # 既存のウィジェットを削除
        for widget in self.calendar_frame.winfo_children():
            widget.destroy()

        # フレーム背景色をグレーに設定(1pxの細い枠線用)
        self.calendar_frame.config(bg="#d0d0d0")

        # 表示年月の更新
        self.calendar_month_label.config(text=f"{self.current_year}年 {self.current_month}月")

        # 曜日ヘッダー
        weekdays = ["日", "月", "火", "水", "木", "金", "土"]
        day_colors = ["#ff0000", "#000000", "#000000", "#000000", "#000000", "#000000", "#00bfff"]
        for i, day in enumerate(weekdays):
            label = tk.Label(
                self.calendar_frame, text=day, font=("Arial", 11, "bold"),
                bg="#fdfdfd", fg=day_colors[i], width=8, height=1
            )
            label.grid(row=0, column=i, sticky="nsew", padx=1, pady=1)

        # カレンダーを日曜日始まりで取得
        cal = calendar.Calendar(firstweekday=6)  # 6=Started from Sunday
        month_days = cal.monthdayscalendar(self.current_year, self.current_month)

        # 固定設定
        DATE_FONT_SIZE = 12  # 日付の数字
        CELL_HEIGHT = 70      # すべてのセルで共通の高さ
        # 日付の表示
        for week_num, week in enumerate(month_days, start=1):
            for day_num, day in enumerate(week):
                # 各セルの土台となるフレーム
                # 高さを明示的に固定します
                calendar_cell_frame = tk.Frame(
                    self.calendar_frame, bg="white", height=CELL_HEIGHT, width=100
                )
                calendar_cell_frame.grid(row=week_num, column=day_num, sticky="nsew", padx=1, pady=1)

                # 重要:中身のテキストサイズによって枠が広がらないように固定
                calendar_cell_frame.grid_propagate(False)
                calendar_cell_frame.pack_propagate(False)

                if day != 0:
                    date_obj = datetime(self.current_year, self.current_month, day)
                    self.holiday_name = jpholiday.is_holiday_name(date_obj.date())

                    # カラー設定
                    if self.holiday_name or day_num == 0:
                        fg_color = "#e60000"
                    elif day_num == 6:
                        fg_color = "#0099ff"
                    else:
                        fg_color = "#333333"

                    # 1. 日付ラベル
                    date_label = tk.Label(
                        calendar_cell_frame, text=str(day), font=("Arial", DATE_FONT_SIZE),
                        bg="white", fg=fg_color
                    )
                    date_label.pack(side=tk.TOP, pady=(5, 0))

                    # 2. 祝日ラベル
                    if self.holiday_name:
                        # 祝日名の長さに応じてフォントサイズを自動調整
                        # 6文字以上の場合はかなり小さくする
                        h_font_size = 7 if len(self.holiday_name) > 5 else 8

                        holiday_label = tk.Label(
                            calendar_cell_frame, text=self.holiday_name, font=("Arial", h_font_size),
                            bg="white", fg=fg_color, justify=tk.CENTER,
                            wraplength=80  # 枠の幅に合わせて自動改行
                        )
                        holiday_label.pack(side=tk.TOP, fill=tk.X, padx=2)

        # 全体のリサイズ設定
        for i in range(7):
            self.calendar_frame.columnconfigure(i, weight=1)
        for i in range(len(month_days) + 1):
            self.calendar_frame.rowconfigure(i, weight=1)

    def _create_memo_section(self):
        """
        左ペイン下部のメモセクション(ヘッダーとフレーム)を生成します。
        """
        # frame of Note
        self.note_container = tk.Frame(self.pw_vertical_left)
        self.pw_vertical_left.add(self.note_container, weight=1)

        # Header for Note
        self.note_header_frame = tk.Frame(self.note_container, bg="#040353", pady=5)
        self.note_header_frame.pack(fill=tk.X)

        # Display selected date
        self.note_date_label = tk.Label(
            self.note_header_frame, text="2026年2月1日", font=("Arial", 10, "bold")
        )
        self.note_date_label.pack(side=tk.LEFT, expand=True)
        self.note_date_label.config(text=f"{self.selected_date.year}年{self.selected_date.month}月{self.selected_date.day}日")

        # Create Button Container
        self.note_button_container = tk.Frame(self.note_header_frame, bg="#f0f0f0")
        self.note_button_container.pack(side=tk.RIGHT, padx=10, pady=5)

        # Save Button
        self.note_save_button = tk.Button(
            self.note_button_container, text="保存", command=self._save_note,
            font=("Arial", 10), width=8, cursor="hand2"
        )
        self.note_save_button.pack(side=tk.LEFT)

    def _save_note(self):
        """ノートを保存します。"""
        print("Save Note")

    def _setup_right_area(self):
        """
        右側のペイン(スケジュール)を構築します。
        """
        self.label_right = tk.Label(
            self.pw_horizontal, text="右・スケジュール", bg="#776c08", fg="white"
        )
        self.pw_horizontal.add(self.label_right, weight=2)


def main():
    """
    アプリケーションのエントリーポイント。
    """
    root = tk.Tk()
    CalendarMemoScheduleApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()

おわりに

今回の更新で、ようやく「カレンダーアプリ」として過去や未来の予定を確認できる最低限の基盤が整いました。特にレイアウトの固定化は、GUI開発において地味ながらも非常に重要なステップです。