Below is one complete example. This program uses only Python’s built‐in libraries (including the built‐in calendar, datetime, and json modules) and builds a Tkinter GUI that shows the current month in a calendar grid. Each day appears as a “box” (a frame with a day label and a small text widget) where users can type in notes. The user can also change the month and year using the top controls, and hit “Update Calendar” to refresh the display. A “Save” button writes all the day notes to a JSON file so that data persists between sessions.
To run the program, simply copy the code into a Python (.py) file and run it.
import tkinter as tk
from tkinter import ttk, messagebox
import calendar
from datetime import datetime
import json
import os
# File name for saving daily notes
DATA_FILENAME = "calendar_data.json"
class CalendarApp:
def __init__(self, master):
self.master = master
master.title("Calendar App")
# Dictionary to hold text widget references
# Keys will be strings in the format "YYYY-MM-DD"
self.day_widgets = {}
# Load saved data if available
self.saved_data = self.load_data()
# Top controls frame for month and year selection.
self.top_frame = ttk.Frame(master)
self.top_frame.pack(pady=10)
# Month selection
months = list(calendar.month_name)[1:] # January to December
self.month_var = tk.StringVar()
current_month = datetime.now().month
self.month_var.set(months[current_month-1])
month_label = ttk.Label(self.top_frame, text="Month:")
month_label.pack(side=tk.LEFT, padx=(0, 5))
self.month_menu = ttk.OptionMenu(self.top_frame, self.month_var, months[current_month-1], *months)
self.month_menu.pack(side=tk.LEFT, padx=(0, 15))
# Year selection (use Spinbox)
self.year_var = tk.IntVar()
current_year = datetime.now().year
self.year_var.set(current_year)
year_label = ttk.Label(self.top_frame, text="Year:")
year_label.pack(side=tk.LEFT, padx=(0, 5))
self.year_spin = tk.Spinbox(self.top_frame, from_=1900, to=2100, textvariable=self.year_var, width=5)
self.year_spin.pack(side=tk.LEFT, padx=(0, 15))
# Update Calendar button
update_btn = ttk.Button(self.top_frame, text="Update Calendar", command=self.update_calendar)
update_btn.pack(side=tk.LEFT, padx=(0, 15))
# Save button
save_btn = ttk.Button(self.top_frame, text="Save", command=self.save_all)
save_btn.pack(side=tk.LEFT)
# Frame for the calendar grid
self.calendar_frame = ttk.Frame(master)
self.calendar_frame.pack(pady=10, padx=10)
# Draw the calendar with the current month/year.
self.draw_calendar(self.year_var.get(), list(calendar.month_name).index(self.month_var.get()))
def load_data(self):
"""Load saved day data from JSON file."""
if os.path.exists(DATA_FILENAME):
try:
with open(DATA_FILENAME, "r") as f:
return json.load(f)
except Exception as ex:
messagebox.showwarning("Load Error", f"Error loading saved data: {ex}")
return {} # return empty dictionary if no file or error
def save_all(self):
"""Save the content of every day cell to file."""
for key, text_widget in self.day_widgets.items():
# Get content from the text widget, strip trailing spaces/newlines.
self.saved_data[key] = text_widget.get("1.0", tk.END).strip()
try:
with open(DATA_FILENAME, "w") as f:
json.dump(self.saved_data, f, indent=4)
messagebox.showinfo("Saved", "Calendar data saved successfully!")
except Exception as ex:
messagebox.showerror("Save Error", f"Error saving data: {ex}")
def update_calendar(self):
"""Update calendar grid based on the selected year and month."""
try:
year = int(self.year_var.get())
except ValueError:
messagebox.showerror("Invalid Year", "Please enter a valid year.")
return
month = list(calendar.month_name).index(self.month_var.get())
self.draw_calendar(year, month)
def draw_calendar(self, year, month):
# First, destroy any previously created widgets in the calendar frame.
for widget in self.calendar_frame.winfo_children():
widget.destroy()
self.day_widgets = {} # reset references
cal = calendar.Calendar(firstweekday=0) # Monday = 0, Sunday = 6.
month_days = cal.monthdayscalendar(year, month)
# Create header row for day names
days_of_week = list(calendar.day_abbr)
for col, day_name in enumerate(days_of_week):
header = ttk.Label(self.calendar_frame, text=day_name, borderwidth=1, relief="solid", anchor="center", width=12)
header.grid(row=0, column=col, padx=1, pady=1, sticky="nsew")
# Create grid for the days: each cell is a frame with day number and a text widget.
for row_index, week in enumerate(month_days, start=1):
for col_index, day in enumerate(week):
cell_frame = ttk.Frame(self.calendar_frame, borderwidth=1, relief="solid")
cell_frame.grid(row=row_index, column=col_index, padx=1, pady=1, sticky="nsew")
if day == 0:
# Empty cell (day not in month)
cell_label = ttk.Label(cell_frame, text="", width=12, anchor="nw")
cell_label.pack(fill="both", expand=True)
else:
# Construct the key for persistence
day_key = f"{year:04d}-{month:02d}-{day:02d}"
# Day label at the top
day_label = ttk.Label(cell_frame, text=str(day), anchor="nw", font=("Arial", 8, "bold"))
day_label.pack(anchor="nw")
# A text widget for user input (notes, events, etc.)
text_widget = tk.Text(cell_frame, width=12, height=4, wrap="word")
text_widget.pack(fill="both", expand=True)
# If saved data exists for this day, populate the widget.
if day_key in self.saved_data:
text_widget.insert("1.0", self.saved_data[day_key])
# Save reference in our dictionary so we can retrieve content later.
self.day_widgets[day_key] = text_widget
# Allow the cells to expand equally (if desired)
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)
if __name__ == "__main__":
root = tk.Tk()
app = CalendarApp(root)
root.mainloop()
How It Works
-
Top Controls:
- The top frame contains an OptionMenu for month selection (populated with the names of the months) and a Spinbox for choosing the year.
- The "Update Calendar" button refreshes the calendar grid to display the selected month and year.
- The "Save" button collects the text entered in each day’s box and writes it to
calendar_data.json.
-
Calendar Grid:
- The program uses the built-in
calendar module to get the weeks and days for any given month.
- Each day is represented by a frame that includes a label (displaying the day number) and a Text widget (for adding notes or events).
- Empty cells (places in the grid that do not correspond to a valid day of the month) are left blank.
-
Saving and Loading:
- When the user clicks "Save", the program writes all entered notes (keyed by date in
YYYY-MM-DD format) to a JSON file.
- On startup, if the file exists, the saved notes are loaded and displayed in the corresponding day boxes.
This program uses only standard libraries and demonstrates how to build an interactive calendar GUI using Tkinter. Enjoy experimenting with it and extending its features!