### Basic Tkinter Setup with tkcalendar Examples Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Provides the basic Tkinter setup required to run the tkcalendar examples, including importing necessary modules and creating the main window. ```python import tkinter as tk from tkinter import ttk from tkcalendar import Calendar, DateEntry import datetime def example1(): def print_sel(): print(cal.selection_get()) cal.see(datetime.date(year=2016, month=2, day=5)) top = tk.Toplevel(root) today = datetime.date.today() mindate = datetime.date(year=2018, month=1, day=21) maxdate = today + datetime.timedelta(days=5) print(mindate, maxdate) cal = Calendar(top, font="Arial 14", selectmode='day', locale='en_US', mindate=mindate, maxdate=maxdate, disabledforeground='red', cursor="hand1", year=2018, month=2, day=5) cal.pack(fill="both", expand=True) ttk.Button(top, text="ok", command=print_sel).pack() def example2(): top = tk.Toplevel(root) cal = Calendar(top, selectmode='none') date = cal.datetime.today() + cal.timedelta(days=2) cal.calevent_create(date, 'Hello World', 'message') cal.calevent_create(date, 'Reminder 2', 'reminder') cal.calevent_create(date + cal.timedelta(days=-2), 'Reminder 1', 'reminder') cal.calevent_create(date + cal.timedelta(days=3), 'Message', 'message') cal.tag_config('reminder', background='red', foreground='yellow') cal.pack(fill="both", expand=True) ttk.Label(top, text="Hover over the events.").pack() def example3(): top = tk.Toplevel(root) ttk.Label(top, text='Choose date').pack(padx=10, pady=10) cal = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2, year=2010) cal.pack(padx=10, pady=10) root = tk.Tk() ttk.Button(root, text='Calendar', command=example1).pack(padx=10, pady=10) # Add buttons for example2 and example3 if needed # ttk.Button(root, text='Events', command=example2).pack(padx=10, pady=10) # ttk.Button(root, text='DateEntry', command=example3).pack(padx=10, pady=10) root.mainloop() ``` -------------------------------- ### Initialize DateEntry with various configurations Source: https://context7.com/j4321/tkcalendar/llms.txt Demonstrates basic DateEntry setup, date range restrictions using mindate/maxdate, and readonly state configuration. ```python ttk.Label(frame, text="Select Date:").grid(row=0, column=0, padx=5, pady=5) date_entry = DateEntry( frame, width=15, year=2024, month=1, day=15, locale='en_US', date_pattern='mm/dd/yyyy', # Custom date pattern background='darkblue', # Calendar header background foreground='white', # Calendar header foreground borderwidth=2, state='normal', # 'normal', 'readonly', or 'disabled' ) date_entry.grid(row=0, column=1, padx=5, pady=5) # DateEntry with date range restrictions ttk.Label(frame, text="Date Range:").grid(row=1, column=0, padx=5, pady=5) today = datetime.date.today() range_entry = DateEntry( frame, width=15, mindate=today, maxdate=today + datetime.timedelta(days=365), locale='en_US', ) range_entry.grid(row=1, column=1, padx=5, pady=5) # Readonly DateEntry (user can only use calendar, not type) ttk.Label(frame, text="Readonly:").grid(row=2, column=0, padx=5, pady=5) readonly_entry = DateEntry(frame, width=15, state='readonly') readonly_entry.grid(row=2, column=1, padx=5, pady=5) ``` -------------------------------- ### Install tkcalendar on Ubuntu Source: https://github.com/j4321/tkcalendar/blob/master/docs/installation.rst Use this command to install tkcalendar on Ubuntu systems via the PPA. ```bash $ sudo add-apt-repository ppa:j-4321-i/ppa $ sudo apt-get update $ sudo apt-get install python3-tkcalendar ``` -------------------------------- ### Initialize and display tkcalendar widgets Source: https://github.com/j4321/tkcalendar/blob/master/docs/example.rst Demonstrates the setup of Calendar and DateEntry widgets within a tkinter application. ```python try: import tkinter as tk from tkinter import ttk except ImportError: import Tkinter as tk import ttk from tkcalendar import Calendar, DateEntry def example1(): def print_sel(): print(cal.selection_get()) top = tk.Toplevel(root) cal = Calendar(top, font="Arial 14", selectmode='day', locale='en_US', cursor="hand1", year=2018, month=2, day=5) cal.pack(fill="both", expand=True) ttk.Button(top, text="ok", command=print_sel).pack() def example2(): top = tk.Toplevel(root) cal = Calendar(top, selectmode='none') date = cal.datetime.today() + cal.timedelta(days=2) cal.calevent_create(date, 'Hello World', 'message') cal.calevent_create(date, 'Reminder 2', 'reminder') cal.calevent_create(date + cal.timedelta(days=-2), 'Reminder 1', 'reminder') cal.calevent_create(date + cal.timedelta(days=3), 'Message', 'message') cal.tag_config('reminder', background='red', foreground='yellow') cal.pack(fill="both", expand=True) ttk.Label(top, text="Hover over the events.").pack() def example3(): top = tk.Toplevel(root) ttk.Label(top, text='Choose date').pack(padx=10, pady=10) cal = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2, year=2010) cal.pack(padx=10, pady=10) root = tk.Tk() ttk.Button(root, text='Calendar', command=example1).pack(padx=10, pady=10) ttk.Button(root, text='Calendar with events', command=example2).pack(padx=10, pady=10) ttk.Button(root, text='DateEntry', command=example3).pack(padx=10, pady=10) root.mainloop() ``` -------------------------------- ### Install tkcalendar via Ubuntu PPA Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Commands to add the PPA and install the package on Ubuntu systems. ```bash $ sudo add-apt-repository ppa:j-4321-i/ppa $ sudo apt-get update $ sudo apt-get install python(3)-tkcalendar ``` -------------------------------- ### Install tkcalendar with pip Source: https://github.com/j4321/tkcalendar/blob/master/docs/installation.rst Install tkcalendar using pip, the Python package installer. ```bash $ pip install tkcalendar ``` -------------------------------- ### Create Tkinter Buttons for Calendar Examples Source: https://github.com/j4321/tkcalendar/blob/master/README.rst This snippet demonstrates how to create Tkinter buttons that trigger different calendar-related examples. It requires the Tkinter library and assumes the existence of 'example2' and 'example3' functions. ```python ttk.Button(root, text='Calendar with events', command=example2).pack(padx=10, pady=10) ttk.Button(root, text='DateEntry', command=example3).pack(padx=10, pady=10) root.mainloop() ``` -------------------------------- ### Initialize DateEntry Widget Source: https://context7.com/j4321/tkcalendar/llms.txt Basic setup for the DateEntry widget within a tkinter frame. ```python import tkinter as tk from tkinter import ttk from tkcalendar import DateEntry import datetime root = tk.Tk() root.title("DateEntry Example") frame = ttk.Frame(root, padding=20) frame.pack() ``` -------------------------------- ### Implement a Date Booking Application with tkcalendar Source: https://context7.com/j4321/tkcalendar/llms.txt This full application setup uses Calendar and DateEntry widgets to manage date-based bookings. It includes event handling to synchronize date selection between the two widgets and manages booking state. ```python import tkinter as tk from tkinter import ttk, messagebox from tkcalendar import Calendar, DateEntry import datetime class DateBookingApp: def __init__(self, root): self.root = root self.root.title("Date Booking Application") # Store booked dates self.bookings = {} self.setup_ui() self.setup_calendar_events() def setup_ui(self): # Main container main_frame = ttk.Frame(self.root, padding=15) main_frame.pack(fill='both', expand=True) # Left panel - Calendar left_frame = ttk.LabelFrame(main_frame, text="Calendar View", padding=10) left_frame.pack(side='left', fill='both', expand=True, padx=(0, 10)) today = datetime.date.today() self.calendar = Calendar( left_frame, selectmode='day', year=today.year, month=today.month, day=today.day, mindate=today, # Can't book past dates maxdate=today + datetime.timedelta(days=90), # Book up to 90 days ahead showweeknumbers=True, weekenddays=[6, 7], weekendbackground='#FFE4E1', weekendforeground='#8B0000', selectbackground='#4169E1', tooltipdelay=300, ) self.calendar.pack(fill='both', expand=True) # Configure event tags self.calendar.tag_config('booked', background='#FF6347', foreground='white') self.calendar.tag_config('available', background='#90EE90', foreground='black') # Right panel - Booking form right_frame = ttk.LabelFrame(main_frame, text="Make a Booking", padding=10) right_frame.pack(side='right', fill='both') # Date selection ttk.Label(right_frame, text="Select Date:").pack(anchor='w', pady=(0, 5)) self.date_entry = DateEntry( right_frame, width=20, mindate=today, maxdate=today + datetime.timedelta(days=90), date_pattern='yyyy-mm-dd', ) self.date_entry.pack(fill='x', pady=(0, 10)) # Name entry ttk.Label(right_frame, text="Your Name:").pack(anchor='w', pady=(0, 5)) self.name_entry = ttk.Entry(right_frame, width=25) self.name_entry.pack(fill='x', pady=(0, 10)) # Description ttk.Label(right_frame, text="Description:").pack(anchor='w', pady=(0, 5)) self.desc_entry = ttk.Entry(right_frame, width=25) self.desc_entry.pack(fill='x', pady=(0, 10)) # Buttons ttk.Button(right_frame, text="Book Date", command=self.make_booking).pack(fill='x', pady=2) ttk.Button(right_frame, text="Cancel Booking", command=self.cancel_booking).pack(fill='x', pady=2) ttk.Button(right_frame, text="View All Bookings", command=self.view_bookings).pack(fill='x', pady=2) # Status self.status_var = tk.StringVar(value="Select a date to book") ttk.Label(right_frame, textvariable=self.status_var, wraplength=200).pack(pady=10) def setup_calendar_events(self): # Sync calendar selection with DateEntry self.calendar.bind("<>", self.on_calendar_select) self.date_entry.bind("<>", self.on_dateentry_select) def on_calendar_select(self, event): date = self.calendar.selection_get() self.date_entry.set_date(date) self.update_status(date) def on_dateentry_select(self, event): date = self.date_entry.get_date() self.calendar.selection_set(date) self.update_status(date) def update_status(self, date): if date in self.bookings: booking = self.bookings[date] self.status_var.set(f"Booked: {booking['name']}\n{booking['desc']}") else: self.status_var.set(f"{date} is available") def make_booking(self): date = self.date_entry.get_date() name = self.name_entry.get().strip() desc = self.desc_entry.get().strip() if not name: messagebox.showwarning("Input Required", "Please enter your name") return if date in self.bookings: messagebox.showwarning("Already Booked", f"{date} is already booked") return # Store booking self.bookings[date] = {'name': name, 'desc': desc} # Add calendar event event_id = self.calendar.calevent_create( date=date, text=f"{name}: {desc}", tags=['booked'] ) self.bookings[date]['event_id'] = event_id # Clear form self.name_entry.delete(0, 'end') self.desc_entry.delete(0, 'end') self.update_status(date) messagebox.showinfo("Success", f"Booking confirmed for {date}") def cancel_booking(self): ``` -------------------------------- ### Manage Calendar Date Selection Source: https://context7.com/j4321/tkcalendar/llms.txt Programmatically get, set, and clear dates, or navigate to specific months. ```python import tkinter as tk from tkcalendar import Calendar import datetime root = tk.Tk() cal = Calendar(root, selectmode='day') cal.pack(padx=10, pady=10) # Get selected date as datetime.date object date_obj = cal.selection_get() print(f"Date object: {date_obj}") # Output: 2024-01-15 # Get selected date as formatted string (locale-dependent) date_str = cal.get_date() print(f"Date string: {date_str}") # Output: 1/15/24 (en_US format) # Set selection using datetime.date cal.selection_set(datetime.date(2024, 6, 20)) # Set selection using datetime.datetime cal.selection_set(datetime.datetime(2024, 7, 4, 12, 30)) # Set selection using string in locale format cal.selection_set("7/4/24") # Clear the selection cal.selection_clear() # Navigate to show a specific month cal.see(datetime.date(2024, 12, 25)) # Get currently displayed month (month, year) tuple month, year = cal.get_displayed_month() print(f"Displaying: {month}/{year}") # Output: Displaying: 12/2024 root.mainloop() ``` -------------------------------- ### Initialize Calendar with Events Source: https://context7.com/j4321/tkcalendar/llms.txt Demonstrates creating a Calendar instance with custom tooltip settings and adding events with tags. ```python import tkinter as tk from tkcalendar import Calendar import datetime root = tk.Tk() root.title("Calendar with Events") cal = Calendar( root, selectmode='none', # Disable day selection for event display tooltipforeground='white', # Tooltip text color tooltipbackground='#333333', # Tooltip background tooltipalpha=0.9, # Tooltip opacity (0-1) tooltipdelay=500, # Delay before showing tooltip (ms) ) cal.pack(padx=10, pady=10, fill='both', expand=True) # Configure tag colors before creating events cal.tag_config('birthday', background='#FF6B6B', foreground='white') cal.tag_config('meeting', background='#4ECDC4', foreground='white') cal.tag_config('holiday', background='#FFD93D', foreground='black') # Create events - returns event ID for later reference today = datetime.date.today() ev1 = cal.calevent_create( date=today + datetime.timedelta(days=2), text='Team Meeting at 10:00 AM', tags=['meeting'] ) ev2 = cal.calevent_create( date=today + datetime.timedelta(days=5), text="Alice's Birthday Party", tags=['birthday'] ) ev3 = cal.calevent_create( date=today + datetime.timedelta(days=5), text='Reminder: Buy gift', tags=['meeting', 'birthday'] # Multiple tags; last tag determines color ) ev4 = cal.calevent_create( date=today + datetime.timedelta(days=10), text='Company Holiday', tags=['holiday'] ) # Get all event IDs all_events = cal.get_calevents() print(f"All event IDs: {all_events}") # Get events by date events_on_day = cal.get_calevents(date=today + datetime.timedelta(days=5)) print(f"Events on day: {events_on_day}") # Get events by tag birthday_events = cal.get_calevents(tag='birthday') print(f"Birthday events: {birthday_events}") # Get event properties event_text = cal.calevent_cget(ev1, 'text') event_date = cal.calevent_cget(ev1, 'date') event_tags = cal.calevent_cget(ev1, 'tags') print(f"Event: {event_text} on {event_date}, tags: {event_tags}") root.mainloop() ``` -------------------------------- ### Create and Configure Calendar Widget Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Demonstrates creating a Calendar widget with specific date ranges, fonts, and selection modes. Use this to set up a calendar with custom appearance and behavior. ```python from tkcalendar import Calendar import datetime # Assuming 'root' is your main Tkinter window # top = tk.Toplevel(root) today = datetime.date.today() mindate = datetime.date(year=2018, month=1, day=21) maxdate = today + datetime.timedelta(days=5) cal = Calendar(top, font="Arial 14", selectmode='day', locale='en_US', mindate=mindate, maxdate=maxdate, disabledforeground='red', cursor="hand1", year=2018, month=2, day=5) ``` -------------------------------- ### Initialize Calendar Widget Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Basic syntax for instantiating the Calendar widget. ```python Calendar(master=None, **kw) ``` -------------------------------- ### Initialize Tkinter Application Source: https://context7.com/j4321/tkcalendar/llms.txt Standard entry point for launching the DateBookingApp within a Tkinter root window. ```python if __name__ == "__main__": root = tk.Tk() app = DateBookingApp(root) root.mainloop() ``` -------------------------------- ### Configure Calendar Options Source: https://context7.com/j4321/tkcalendar/llms.txt Demonstrates how to dynamically update widget properties and appearance using the configure method. ```python import tkinter as tk from tkinter import ttk from tkcalendar import Calendar import datetime root = tk.Tk() root.title("Calendar Configuration") frame = ttk.Frame(root, padding=10) frame.pack() cal = Calendar(frame, selectmode='day') cal.pack(pady=10) controls = ttk.Frame(frame) controls.pack() def toggle_weeknumbers(): current = cal['showweeknumbers'] cal.configure(showweeknumbers=not current) def toggle_othermonth(): current = cal['showothermonthdays'] cal.configure(showothermonthdays=not current) def change_firstweekday(): current = cal['firstweekday'] new_day = 'sunday' if current == 'monday' else 'monday' cal.configure(firstweekday=new_day) def set_date_range(): today = datetime.date.today() cal.configure( mindate=today - datetime.timedelta(days=30), maxdate=today + datetime.timedelta(days=30) ) def clear_date_range(): cal.configure(mindate=None, maxdate=None) def change_colors(): cal.configure( background='#2196F3', foreground='white', selectbackground='#FF5722', selectforeground='white', normalbackground='#E3F2FD', weekendbackground='#BBDEFB', ) def change_locale(): # Change locale (requires babel) current = cal['locale'] new_locale = 'fr_FR' if current == 'en_US' else 'en_US' cal.configure(locale=new_locale) def disable_calendar(): current = cal['state'] new_state = 'disabled' if current == 'normal' else 'normal' cal.configure(state=new_state) def get_all_options(): # Get list of all configurable options print("Available options:", cal.keys()) # Get specific option value print(f"Current font: {cal['font']}") print(f"Current locale: {cal['locale']}") print(f"Current selectmode: {cal['selectmode']}") ttk.Button(controls, text="Toggle Week Numbers", command=toggle_weeknumbers).grid(row=0, column=0, padx=2, pady=2) ttk.Button(controls, text="Toggle Other Month Days", command=toggle_othermonth).grid(row=0, column=1, padx=2, pady=2) ttk.Button(controls, text="Change First Weekday", command=change_firstweekday).grid(row=1, column=0, padx=2, pady=2) ttk.Button(controls, text="Set Date Range", command=set_date_range).grid(row=1, column=1, padx=2, pady=2) ttk.Button(controls, text="Clear Date Range", command=clear_date_range).grid(row=2, column=0, padx=2, pady=2) ttk.Button(controls, text="Change Colors", command=change_colors).grid(row=2, column=1, padx=2, pady=2) ttk.Button(controls, text="Change Locale", command=change_locale).grid(row=3, column=0, padx=2, pady=2) ttk.Button(controls, text="Toggle Disabled", command=disable_calendar).grid(row=3, column=1, padx=2, pady=2) ttk.Button(controls, text="Print Options", command=get_all_options).grid(row=4, column=0, columnspan=2, pady=5) root.mainloop() ``` -------------------------------- ### Initialize DateEntry Widget Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Syntax for creating a new DateEntry instance. ```python DateEntry(master=None, **kw) ``` -------------------------------- ### Tkinter Calendar Bound to StringVar Source: https://context7.com/j4321/tkcalendar/llms.txt Use this to create a calendar widget that is synchronized with a Tkinter StringVar. Changes to the StringVar will update the calendar, and vice-versa. Ensure the 'tkcalendar' library is installed. ```python from tkinter import * from tkinter import ttk from tkcalendar import Calendar root = Tk() root.title("Calendar StringVar Example") frame = ttk.Frame(root, padding="10") frame.pack(pady=10, padx=10) date_var = tk.StringVar() # Calendar bound to StringVar cal = Calendar( frame, selectmode='day', textvariable=date_var, # Bind to StringVar date_pattern='yyyy-mm-dd', ) cal.pack(pady=10) # Entry showing the same StringVar ttk.Label(frame, text="Date (editable):").pack(anchor='w') entry = ttk.Entry(frame, textvariable=date_var, width=20) entry.pack(anchor='w', pady=5) # Label showing the StringVar value label = ttk.Label(frame, textvariable=date_var, font=('Arial', 14, 'bold')) label.pack(pady=10) def on_var_change(*args): print(f"Date changed to: {date_var.get()}") # Trace changes to the StringVar date_var.trace_add('write', on_var_change) # Changing the StringVar updates the calendar def set_christmas(): date_var.set('2024-12-25') def set_newyear(): date_var.set('2025-01-01') ttk.Button(frame, text="Set Christmas", command=set_christmas).pack(pady=2) ttk.Button(frame, text="Set New Year", command=set_newyear).pack(pady=2) root.mainloop() ``` -------------------------------- ### Calendar Widget Initialization Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Documentation for the Calendar widget constructor and its configurable options. ```APIDOC ## Calendar(master=None, **kw) ### Description Initializes a new Calendar widget for Tkinter. ### Parameters #### Request Body (Widget Options) - **cursor** (str) - Optional - Cursor to display when the pointer is in the widget - **font** (str/Font) - Optional - Font of the calendar - **borderwidth** (int) - Optional - Width of the border around the calendar - **state** (str) - Optional - "normal" or "disabled" (unresponsive widget) - **year** (int) - Optional - Initially displayed year, default is current year - **month** (int) - Optional - Initially displayed month, default is current month - **day** (int) - Optional - Initially selected day - **firstweekday** (str) - Optional - "monday" or "sunday" - **weekenddays** (list) - Optional - List of integers for weekend days - **mindate** (datetime) - Optional - Minimum allowed date - **maxdate** (datetime) - Optional - Maximum allowed date - **showweeknumbers** (bool) - Optional - Whether to display week numbers (default True) - **showothermonthdays** (bool) - Optional - Whether to display days from other months (default True) - **locale** (str) - Optional - Locale to use (e.g., 'en_US') - **date_pattern** (str) - Optional - Pattern to format the date (e.g., 'y-mm-dd') - **selectmode** (str) - Optional - "none" or "day" (default) - **textvariable** (StringVar) - Optional - Connects the selected date to a variable - **background** (str) - Optional - Background color of calendar border and month/year name - **foreground** (str) - Optional - Foreground color of month/year name - **selectbackground** (str) - Optional - Background color of selected day - **selectforeground** (str) - Optional - Foreground color of selected day ``` -------------------------------- ### Initialize Calendar Widget Source: https://context7.com/j4321/tkcalendar/llms.txt Create a Calendar widget with custom styling, locale settings, and event binding. ```python import tkinter as tk from tkinter import ttk from tkcalendar import Calendar import datetime root = tk.Tk() root.title("Calendar Example") # Create a basic calendar with custom options cal = Calendar( root, selectmode='day', # Enable day selection year=2024, # Initial year month=1, # Initial month day=15, # Initially selected day locale='en_US', # Locale for date formatting font="Arial 12", # Font for calendar cursor="hand1", # Cursor when hovering showweeknumbers=True, # Display week numbers showothermonthdays=True, # Show days from adjacent months firstweekday='monday', # First day of week background='gray30', # Header background color foreground='white', # Header text color selectbackground='#1E90FF', # Selected day background selectforeground='white', # Selected day text color normalbackground='white', # Normal day background normalforeground='black', # Normal day text color weekendbackground='#F0E68C',# Weekend background color weekendforeground='black', # Weekend text color headersbackground='gray70', # Day names header background headersforeground='black', # Day names header foreground bordercolor='gray70', # Border color between days ) cal.pack(padx=10, pady=10) # Get selected date as datetime.date object def on_select(): selected = cal.selection_get() # Returns datetime.date print(f"Selected date: {selected}") print(f"Formatted: {cal.get_date()}") # Returns formatted string # Bind to selection event cal.bind("<>", lambda e: on_select()) ttk.Button(root, text="Get Date", command=on_select).pack(pady=5) root.mainloop() ``` -------------------------------- ### DateEntry Widget Initialization Source: https://github.com/j4321/tkcalendar/blob/master/docs/DateEntry.rst Details on how to initialize the DateEntry widget and its available options. ```APIDOC ## DateEntry Widget ### Description Creates an entry widget with a drop-down calendar for date selection. The entry content is reset to the last valid date if the user input is not a valid date upon losing focus. ### Method __init__ ### Parameters #### Keyword Options - **master** (widget) - Optional - The parent widget. - **class** (str) - Optional - Widget class name. - **cursor** (str) - Optional - Cursor shape when the mouse hovers over the widget. - **style** (str) - Optional - Widget style. - **takefocus** (int) - Optional - Whether the widget should receive focus. - **xscrollcommand** (callable) - Optional - Command to control horizontal scrolling. - **exportselection** (bool) - Optional - Whether to export selection to the clipboard. - **justify** (str) - Optional - Text justification (left, center, right). - **show** (str) - Optional - Character to display for hidden input (e.g., passwords). - **state** (str) - Optional - Widget state (normal, disabled, readonly). - **textvariable** (StringVar) - Optional - Tkinter variable to link to the entry's content. - **width** (int) - Optional - Width of the entry widget. - **calendar_cursor** (str) - Optional - Cursor shape for the calendar popup. ### Request Example ```python from tkcalendar import DateEntry # Example with default options date_entry = DateEntry(root) # Example with custom options date_entry = DateEntry(root, width=12, background='red', foreground='white', borderwidth=2, calendar_cursor='hand1', date_pattern='dd/mm/yyyy') ``` ### Response #### Success Response (200) N/A - This is a widget initialization, not an API endpoint. #### Response Example N/A ``` -------------------------------- ### Implement custom date patterns Source: https://context7.com/j4321/tkcalendar/llms.txt Demonstrates how to use date_pattern to format date displays in DateEntry and Calendar widgets. ```python import tkinter as tk from tkinter import ttk from tkcalendar import Calendar, DateEntry import datetime root = tk.Tk() root.title("Custom Date Patterns") frame = ttk.Frame(root, padding=20) frame.pack() # Date patterns use: y (year), m (month), d (day) # y/yy = 2-digit year, yyy+ = full year # m = month without padding, mm = 2-digit month # d = day without padding, dd = 2-digit day patterns = [ ('Default (locale)', None), ('ISO Format', 'yyyy-mm-dd'), # 2024-01-15 ('US Format', 'mm/dd/yyyy'), # 01/15/2024 ('European', 'dd/mm/yyyy'), # 15/01/2024 ('Short Year', 'm/d/yy'), # 1/15/24 ('Compact', 'yyyymmdd'), # 20240115 ] for i, (label, pattern) in enumerate(patterns): ttk.Label(frame, text=f"{label}:").grid(row=i, column=0, sticky='w', padx=5, pady=2) if pattern: entry = DateEntry(frame, width=15, date_pattern=pattern, year=2024, month=1, day=15) else: entry = DateEntry(frame, width=15, locale='en_US', year=2024, month=1, day=15) entry.grid(row=i, column=1, padx=5, pady=2) # Calendar with custom pattern ttk.Label(frame, text="Calendar:").grid(row=len(patterns), column=0, sticky='w', padx=5, pady=10) cal = Calendar(frame, date_pattern='yyyy-mm-dd', year=2024, month=1, day=15) cal.grid(row=len(patterns), column=1, padx=5, pady=10) ``` -------------------------------- ### Use StringVar with Calendar Source: https://context7.com/j4321/tkcalendar/llms.txt Initializes a StringVar for tracking calendar date changes. ```python import tkinter as tk from tkinter import ttk from tkcalendar import Calendar root = tk.Tk() root.title("Calendar with StringVar") frame = ttk.Frame(root, padding=20) frame.pack() # Create StringVar to hold selected date date_var = tk.StringVar() ``` -------------------------------- ### Display Events on Calendar Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Shows how to add and configure events to be displayed on the Calendar widget. Events can have descriptions and be styled with different tags. ```python cal.calevent_create(date, 'Hello World', 'message') cal.calevent_create(date, 'Reminder 2', 'reminder') cal.calevent_create(date + cal.timedelta(days=-2), 'Reminder 1', 'reminder') cal.calevent_create(date + cal.timedelta(days=3), 'Message', 'message') cal.tag_config('reminder', background='red', foreground='yellow') ``` -------------------------------- ### Create DateEntry Widget Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Illustrates the creation of a DateEntry widget, which provides a text entry field for selecting dates with a dropdown calendar. Useful for forms requiring date input. ```python from tkcalendar import DateEntry # Assuming 'top' is a Tkinter window or frame cal = DateEntry(top, width=12, background='darkblue', foreground='white', borderwidth=2, year=2010) ``` -------------------------------- ### Manage Calendar Events Dynamically Source: https://context7.com/j4321/tkcalendar/llms.txt Shows how to modify, reorder, and remove calendar events, as well as perform tag operations. ```python import tkinter as tk from tkinter import ttk from tkcalendar import Calendar import datetime root = tk.Tk() cal = Calendar(root, selectmode='none') cal.pack(padx=10, pady=10) # Setup tags cal.tag_config('important', background='red', foreground='white') cal.tag_config('normal', background='blue', foreground='white') today = datetime.date.today() # Create multiple events on same date ev1 = cal.calevent_create(today, 'First Event', ['normal']) ev2 = cal.calevent_create(today, 'Second Event', ['important']) ev3 = cal.calevent_create(today, 'Third Event', ['normal']) def modify_event(): # Modify event text, date, or tags cal.calevent_configure(ev1, text='Updated First Event') cal.calevent_configure(ev2, tags=['normal']) cal.calevent_configure(ev3, date=today + datetime.timedelta(days=1)) def reorder_events(): # Raise event to top of tooltip list cal.calevent_raise(ev2) # Put ev2 at top # Lower event to bottom of tooltip list cal.calevent_lower(ev1) # Put ev1 at bottom # Raise above specific event cal.calevent_raise(ev3, above=ev2) # Put ev3 above ev2 def remove_events(): # Remove single event by ID cal.calevent_remove(ev1) # Remove all events with specific tag cal.calevent_remove(tag='normal') # Remove all events on a date cal.calevent_remove(date=today) # Remove all events cal.calevent_remove('all') def tag_operations(): # Get tag color configuration bg = cal.tag_cget('important', 'background') fg = cal.tag_cget('important', 'foreground') print(f"Important tag: bg={bg}, fg={fg}") # Get all tag names tags = cal.tag_names() print(f"All tags: {tags}") # Delete a tag (removes from all events) cal.tag_delete('normal') ttk.Button(root, text="Modify", command=modify_event).pack() ttk.Button(root, text="Reorder", command=reorder_events).pack() ttk.Button(root, text="Remove", command=remove_events).pack() ttk.Button(root, text="Tag Ops", command=tag_operations).pack() root.mainloop() ``` -------------------------------- ### Handle Calendar Virtual Events Source: https://context7.com/j4321/tkcalendar/llms.txt Binds custom virtual events to handle user interactions like date selection and month navigation. ```python import tkinter as tk from tkinter import ttk from tkcalendar import Calendar root = tk.Tk() root.title("Calendar Events") frame = ttk.Frame(root, padding=20) frame.pack() cal = Calendar(frame, selectmode='day') cal.pack() output = tk.Text(frame, height=5, width=40) output.pack(pady=10) def on_date_selected(event): """Triggered when user clicks on a day.""" date = cal.selection_get() output.insert('end', f"Selected: {date}\n") output.see('end') def on_month_changed(event): """Triggered when user navigates to different month.""" month, year = cal.get_displayed_month() output.insert('end', f"Month changed to: {month}/{year}\n") output.see('end') # Bind virtual events cal.bind("<>", on_date_selected) cal.bind("<>", on_month_changed) # For DateEntry widget ttk.Label(frame, text="DateEntry:").pack(anchor='w', pady=(10, 0)) date_entry = DateEntry(frame) date_entry.pack(anchor='w') def on_dateentry_selected(event): """Triggered when user selects date from DateEntry dropdown.""" date = date_entry.get_date() output.insert('end', f"DateEntry selected: {date}\n") output.see('end') date_entry.bind("<>", on_dateentry_selected) root.mainloop() ``` -------------------------------- ### DateEntry Widget Methods Source: https://github.com/j4321/tkcalendar/blob/master/README.rst Methods for interacting with the DateEntry widget, including toggling the calendar display and managing date values. ```APIDOC ## drop_down() ### Description Display or withdraw the drop-down calendar depending on its current state. ## get_date() ### Description Return the selected date as a datetime.date instance. ## set_date(date) ### Description Set the value of the DateEntry to the specified date. ### Parameters #### Request Body - **date** (datetime.date or string) - Required - A datetime.date instance or a string corresponding to the date format "%x" in the Calendar locale. ``` -------------------------------- ### Interact with DateEntry values Source: https://context7.com/j4321/tkcalendar/llms.txt Methods for retrieving and setting dates using datetime objects or strings, and binding to selection events. ```python def get_dates(): # Get date as datetime.date object date_obj = date_entry.get_date() print(f"Date object: {date_obj}") # Get date as string from entry date_str = date_entry.get() print(f"Date string: {date_str}") def set_date(): # Set date using datetime.date date_entry.set_date(datetime.date(2024, 12, 25)) # Set date using datetime.datetime range_entry.set_date(datetime.datetime(2024, 6, 15, 10, 30)) # Set date using string readonly_entry.set_date("07/04/2024") # Bind to selection event date_entry.bind("<>", lambda e: print(f"Selected: {date_entry.get_date()}")) ttk.Button(frame, text="Get Dates", command=get_dates).grid(row=3, column=0, pady=10) ttk.Button(frame, text="Set Dates", command=set_date).grid(row=3, column=1, pady=10) root.mainloop() ``` -------------------------------- ### Calendar Styling Options Source: https://github.com/j4321/tkcalendar/blob/master/docs/Calendar.rst Configuration options for customizing the appearance of disabled days and tooltips in the calendar. ```APIDOC ## Calendar Styling Configuration ### Disabled Day Options - **disableddaybackground** (str) - Background color of days in disabled state - **disableddayforeground** (str) - Foreground color of days in disabled state ### Tooltip Options - **tooltipforeground** (str) - Tooltip text color - **tooltipbackground** (str) - Tooltip background color - **tooltipalpha** (float) - Tooltip opacity between 0 and 1 - **tooltipdelay** (int) - Delay in ms before displaying the tooltip ``` -------------------------------- ### Cancel Booking and View Bookings Methods Source: https://context7.com/j4321/tkcalendar/llms.txt Logic for removing a booking event from the calendar and displaying all current bookings in a message box. ```python date = self.date_entry.get_date() if date not in self.bookings: messagebox.showwarning("No Booking", f"No booking found for {date}") return # Remove calendar event event_id = self.bookings[date].get('event_id') if event_id is not None: self.calendar.calevent_remove(event_id) # Remove booking del self.bookings[date] self.update_status(date) messagebox.showinfo("Cancelled", f"Booking for {date} has been cancelled") def view_bookings(self): if not self.bookings: messagebox.showinfo("Bookings", "No bookings yet") return booking_list = [] for date in sorted(self.bookings.keys()): b = self.bookings[date] booking_list.append(f"{date}: {b['name']} - {b['desc']}") messagebox.showinfo("All Bookings", "\n".join(booking_list)) ```