Kazuki's Blog

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

tkinterを利用したカレンダーWidgetの作成(その11: メモの有無を可視化と削除機能の追加)

はじめに

PythonのTkinterを使って、カレンダーアプリを開発していくシリーズの第11回目です。今回は、以下の機能を追加しました。

  1. メモがある日の背景色を変更(可視化)
  2. メモの削除機能の追加

1. 今回の主な更新ポイント

1. メモの有無をカレンダーに反映

カレンダーを描画する際、データベースを照合してメモが存在する日付の背景色を薄い緑色(#e8f5e9)に変更するようにしました。また、現在選択している日付は薄い黄色(#fff9c4)で表示し、視認性を向上させています。

2. ノートの削除機能の実装

「削除」ボタンを新たに追加しました。誤操作を防ぐため、削除実行前には確認ダイアログ(messagebox.askyesno)を表示し、削除後は即座にカレンダーの色が更新されるように作り込んでいます。

2. 実装したコード

import tkinter as tk
from tkinter import scrolledtext, messagebox
from datetime import datetime
import calendar
import jpholiday
import sqlite3

APP_NAME = "カレンダーアプリ - ノート機能付き"
WIN_SIZE = "1200x500"
DB_PATH = "calendar_notes.db"

class CalendarApp:
    def __init__(self, root):
        self.root = root
        self.root.title(APP_NAME)
        self.root.geometry(WIN_SIZE)
        self.current_year = datetime.now().year
        self.current_month = datetime.now().month
        self.selected_date = datetime.now().date()

        self.init_database()
        self.create_widgets()
        self.display_calendar()
        self.load_note()

    def init_database(self):
        self.db_path = DB_PATH
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute('''
                create table if not exists cal_notes (
                    date text primary key,
                    filename text not null,
                    file_data blob not null,
                    updated_at datetime default current_timestamp
                )           
            ''')
            conn.commit()

    def create_widgets(self):
        main_container = tk.Frame(self.root)
        main_container.pack(fill=tk.BOTH, expand=True)

        # カレンダーエリア
        calendar_container = tk.Frame(main_container, width=600)
        calendar_container.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        header_frame = tk.Frame(calendar_container, bg="#f0f0f0", pady=10)
        header_frame.pack(fill=tk.X)

        self.prev_button = tk.Button(header_frame, text="< 前月", command=self.previous_month, width=8)
        self.prev_button.pack(side=tk.LEFT, padx=20)

        self.month_label = tk.Label(header_frame, text="YYYY/MM", font=("Arial", 16, "bold"), bg="#f0f0f0")
        self.month_label.pack(side=tk.LEFT, expand=True)

        self.next_button = tk.Button(header_frame, text="次月 >", command=self.next_month, width=8)
        self.next_button.pack(side=tk.RIGHT, padx=20)

        self.calendar_frame = tk.Frame(calendar_container, bg="white")
        self.calendar_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # ノートエリア
        note_container = tk.Frame(main_container, width=600, bg="#f5f5f5")
        note_container.pack(side=tk.RIGHT, fill=tk.BOTH, expand=False)
        note_container.pack_propagate(False)

        note_header = tk.Frame(note_container, bg="#f0f0f0", height=60)
        note_header.pack(fill=tk.X)
        note_header.pack_propagate(False)

        self.note_date_label = tk.Label(note_header, text="YYYY/MM/DD", font=("Arial", 12, "bold"), bg="#f0f0f0")
        self.note_date_label.pack(side=tk.LEFT, padx=15, pady=10)

        # ボタンコンテナ(削除と保存)
        button_container = tk.Frame(note_header, bg="#f0f0f0")
        button_container.pack(side=tk.RIGHT, padx=15, pady=10)

        self.delete_button = tk.Button(button_container, text="削除", command=self.delete_note, width=8, cursor="hand2")
        self.delete_button.pack(side=tk.LEFT, padx=5)

        self.save_button = tk.Button(button_container, text="保存", command=self.save_note, width=8, cursor="hand2")
        self.save_button.pack(side=tk.LEFT)

        note_text_frame = tk.Frame(note_container, bg="white")
        note_text_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        self.note_text = scrolledtext.ScrolledText(note_text_frame, wrap=tk.WORD, font=("Arial", 11))
        self.note_text.pack(fill=tk.BOTH, expand=True)

        self.placeholder_text = "ここにメモを入力してください...\n\nMarkdown形式で記述できます:\n# 見出し1\n## 見出し2\n- リスト項目\n**太字**\n*斜体*"
        self.show_placeholder()
        self.note_text.bind("<FocusIn>", self.hide_placeholder)
        self.note_text.bind("<FocusOut>", self.show_placeholder_if_empty)
    
    # --- 中略 (placeholder管理, previous/next_month 等) ---

    def display_calendar(self):
        for widget in self.calendar_frame.winfo_children():
            widget.destroy()

        self.month_label.config(text=f"{self.current_year}年 {self.current_month}月")
    
        # メモが存在する日付をリストアップ
        dates_with_notes = []
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            month_str = f"{self.current_year}-{self.current_month:02d}-%"
            cursor.execute("select date from cal_notes where date like ?", (month_str,))
            dates_with_notes = [row[0] for row in cursor.fetchall()]

        # 曜日の描画...
        # カレンダーの描画 (抜粋)
        cal = calendar.Calendar(firstweekday=6)
        month_days = cal.monthdayscalendar(self.current_year, self.current_month)

        for week_num, week in enumerate(month_days, start=1):
            for day_num, day in enumerate(week):
                if day != 0:
                    date_obj = datetime(self.current_year, self.current_month, day)
                    date_str = date_obj.strftime("%Y-%m-%d")
                    
                    # 背景色の決定ロジック
                    if date_obj.date() == self.selected_date:
                        bg_color = "#fff9c4" # 選択中
                    elif date_str in dates_with_notes:
                        bg_color = "#e8f5e9" # メモあり
                    else:
                        bg_color = "white"

                    label = tk.Label(self.calendar_frame, text=str(day), bg=bg_color, relief=tk.RIDGE, borderwidth=1)
                    label.bind("<Button-1>", lambda e, d=date_obj.date(): self.select_date(d))
                    label.grid(row=week_num, column=day_num, sticky="nsew", padx=1, pady=1)

    def delete_note(self):
        date_str = self.selected_date.strftime("%Y-%m-%d")
        # 存在確認
        with sqlite3.connect(self.db_path) as conn:
            cursor = conn.cursor()
            cursor.execute("select filename from cal_notes where date = ?", (date_str,))
            if not cursor.fetchone():
                messagebox.showinfo("削除", "削除するノートがありません。")
                return
        
        if messagebox.askyesno("削除確認", f"{date_str} のノートを削除しますか?"):
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute("delete from cal_notes where date = ?", (date_str,))
                conn.commit()
            
            self.note_text.delete("1.0", tk.END)
            self.show_placeholder()
            self.display_calendar() # カレンダーの色を更新
            messagebox.showinfo("削除完了", f"{date_str} のノートを削除しました。")

    # --- 以下略 ---

おわりに

今回、「メモの有無を色で表現する」 という機能を実装したことで、アプリとしての完成度がグッと高まりました。

  • display_calendar メソッドの中でSQLの LIKE 句を使い、表示中の月のメモを一度に取得して判定するように工夫しました。
  • 削除機能の実装により、不要なデータの整理も可能になりました。

TkinterでのGUI開発は、この様に少しずつ「不便」を「便利」に変えていく過程がとても楽しいです!

次回からは、予定と実績のスケジュール管理ができるWidgetの作成をしていきたいと思います。最終的には、カレンダー・ノート・スケジュールWidgetの統合を目指していきたいと思います。