アットウィキロゴ

カレンダー

各種AIに書いてもらったカレンダーです。python3-tk(Tkinter)と python3-requests が必要です。
$ python3 tkcal.py とでもして実行します。

import tkinter as tk
import tkinter.font as tkfont
import requests, calendar, os
from datetime import date, datetime

# ==================== 設定 ====================

# API & Cache
HOLIDAY_API_URL = "https://holidays-jp.github.io/api/v1/date.csv"
HOLIDAY_CACHE = os.path.join(os.path.expanduser("~"), ".cache", "date.csv")

# Window Settings
WINDOW_X = 28
WINDOW_Y = 0
WINDOW_WIDTH = 220
WINDOW_HEIGHT = 185

# Font Settings
FONT_SIZE = 10
TITLE_SIZE = 12
BUTTON_SIZE = 11
FONT_CANDIDATES = [
    "Noto Sans CJK JP", "IPAゴシック", "IPAGothic",
    "TakaoGothic", "VL Gothic", "DejaVu Sans"
]

# Colors
COLOR_HEADER = "#245000"
COLOR_TEXT = "#333333"
COLOR_SUN = "#dc3545"      # 日曜
COLOR_SAT = "#2878c8"       # 土曜
COLOR_TODAY_BG = "#ffe082"  # 今日の背景
COLOR_CELL_BG = "#ffffee"   # 通常の背景
COLOR_WHITE = "white"

calendar.setfirstweekday(calendar.MONDAY)

# ==================== ロジック層 ====================

def select_font(root):
    available = tkfont.families(root)
    for font in FONT_CANDIDATES:
        if font in available:
            return font
    return "TkDefaultFont"

def load_holiday_cache():
    if not os.path.exists(HOLIDAY_CACHE):
        return None
    try:
        with open(HOLIDAY_CACHE, "r", encoding="utf-8") as f:
            # CSVの各行を読み込んで、日付のセットを返す
            dates = set()
            for line in f:
                date_str = line.split(",")[0].strip()
                # 空行やヘッダーを除外するための簡易的なチェック (YYYY-MM-DD形式)
                if date_str and "-" in date_str and len(date_str) == 10:
                    dates.add(date_str)
            return dates if dates else None
    except Exception:
        return None

def save_holiday_cache(raw_content):
    try:
        cache_dir = os.path.dirname(HOLIDAY_CACHE)
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir, exist_ok=True)
            
        with open(HOLIDAY_CACHE, "w", encoding="utf-8") as f:
            f.write(raw_content)
        return True
    except Exception as e:
        print(f"Cache Save Error: {e}")
        return False


def fetch_holidays():
    today = date.today()
    cached_data = load_holiday_cache()
    should_download = False

    if cached_data is None:
        should_download = True
    elif today.weekday() == 0:  # 月曜日に1回更新
        try:
            mtime = datetime.fromtimestamp(
                os.path.getmtime(HOLIDAY_CACHE)
            ).date()
            if mtime != today:
                should_download = True
        except Exception:
            should_download = True

    if should_download:
        try:
            response = requests.get(HOLIDAY_API_URL, timeout=5)
            response.raise_for_status()

            raw_text = response.text

            # CSVの内容を検証して日付のセットを作成
            dates = set()

            for line_no, line in enumerate(raw_text.splitlines(), start=1):
                parts = line.split(",", 1)

                if len(parts) != 2:
                    raise ValueError(
                        f"CSV format error (line {line_no})"
                    )

                date_str = parts[0].strip()
                holiday_name = parts[1].strip()

                try:
                    datetime.strptime(date_str, "%Y-%m-%d")
                except ValueError:
                    raise ValueError(
                        f"Invalid date (line {line_no}): {date_str}"
                    )

                if not holiday_name:
                    raise ValueError(
                        f"Empty holiday name (line {line_no})"
                    )

                dates.add(date_str)

            if not dates:
                raise ValueError("No holiday data")

            # 正常なデータだけキャッシュに保存
            save_holiday_cache(raw_text)

            return dates, None

        except Exception as e:
            return (
                cached_data if cached_data is not None else set(),
                f"Error: {e}"
            )

    return cached_data, None

# ==================== UIコンポーネント ====================

class CustomCalendar(tk.Frame):
    def __init__(self, parent, font, holidays):
        super().__init__(parent, bg=COLOR_WHITE)
        self.font = font
        self.holidays = holidays
        self.year = date.today().year
        self.month = date.today().month
        
        # グリッドの設定(一度だけ実行)
        for col in range(7):
            self.grid_columnconfigure(col, weight=1, uniform="calendar")
            
        self.create_calendar()

    def create_calendar(self):
        # ウィジェットのクリア
        for widget in self.winfo_children():
            widget.destroy()

        # ヘッダー部分
        header = tk.Frame(self, bg=COLOR_HEADER)
        header.grid(row=0, column=0, columnspan=7, sticky="ew")
        header.grid_columnconfigure(1, weight=5)

        tk.Button(header, text="<", font=(self.font, BUTTON_SIZE),
                   bg=COLOR_HEADER, fg="white", relief="flat", bd=0,
                   command=self.previous_month).grid(row=0, column=0, sticky="ew")

        tk.Label(header, text=f"{self.year}年 {self.month}月",
                  font=(self.font, TITLE_SIZE, "bold"), bg=COLOR_HEADER, 
                  fg="white", pady=4).grid(row=0, column=1, sticky="ew")

        tk.Button(header, text=">", font=(self.font, BUTTON_SIZE),
                   bg=COLOR_HEADER, fg="white", relief="flat", bd=0,
                   command=self.next_month).grid(row=0, column=2, sticky="ew")

        # 曜日ラベル
        weekdays = ["月", "火", "水", "木", "金", "土", "日"]
        for i, weekday in enumerate(weekdays):
            color = COLOR_SUN if i == 6 else (COLOR_SAT if i == 5 else COLOR_TEXT)
            tk.Label(self, text=weekday, font=(self.font, FONT_SIZE, "bold"),
                     bg=COLOR_WHITE, fg=color, pady=2).grid(row=1, column=i, sticky="nsew")

        # 日付の描画
        weeks = calendar.monthcalendar(self.year, self.month)
        today_dt = date.today()

        for w_idx, week in enumerate(weeks):
            for d_idx, day in enumerate(week):
                if day == 0:
                    text = ""
                    bg = COLOR_WHITE
                    fg = COLOR_TEXT
                else:
                    text = str(day)
                    date_str = f"{self.year}-{self.month:02d}-{day:02d}"
                    is_holiday = date_str in self.holidays
                    is_today = (today_dt.year == self.year and 
                                 today_dt.month == self.month and 
                                 today_dt.day == day)

                    # 色決定
                    if is_holiday or d_idx == 6:
                        fg = COLOR_SUN
                    elif d_idx == 5:
                        fg = COLOR_SAT
                    else:
                        fg = COLOR_TEXT
                    
                    bg = COLOR_TODAY_BG if is_today else COLOR_CELL_BG

                tk.Label(self, text=text, font=(self.font, FONT_SIZE, "bold"),
                         width=2, height=1, bg=bg, fg=fg, 
                         anchor="center", padx=1, pady=1).grid(row=w_idx+2, column=d_idx, sticky="nsew")

    def previous_month(self):
        self.month -= 1
        if self.month < 1:
            self.month = 12
            self.year -= 1
        self.create_calendar()

    def next_month(self):
        self.month += 1
        if self.month > 12:
            self.month = 1
            self.year += 1
        self.create_calendar()

# ==================== メイン実行 ====================

def main():
    root = tk.Tk()
    root.geometry(f"{WINDOW_WIDTH}x{WINDOW_HEIGHT}+{WINDOW_X}+{WINDOW_Y}")
    root.resizable(False, False)
    root.configure(bg=COLOR_WHITE)

    FONT = select_font(root)
    HOLIDAYS, HOLIDAY_ERROR = fetch_holidays()

    root.title("祝日取得エラー" if HOLIDAY_ERROR else "カレンダー")

    cal = CustomCalendar(root, FONT, HOLIDAYS)
    cal.pack(fill="both", expand=True)

    root.mainloop()

if __name__ == "__main__":
    main()
最終更新:2026年11月18日 19:53