tkcalendar Calendar & Date selection


Mastering Date Selection in #Python #Tkinter: A Comprehensive Guide to tkcalendar

At Command prompt enter pip install tkcalendar
pip install tkcalendar
import tkinter  as tk 
from tkcalendar import Calendar 
my_w = tk.Tk()
my_w.geometry("380x200")  # width and height of window 
cal=Calendar(my_w,selectmode='day',year=2021,month=8,day=23)
cal.grid(row=1,column=1,padx=20)
my_w.mainloop()  
tkcalendar date picker
If we don't specify any year , month or day then it will show current year month and day as default selected.
cal=Calendar(my_w,selectmode='day')
Take Date as user input through Calendar by using DateEntry

Collecting selected date: get_date()

tkcalendar get_date() to read date selection
We will read and display the selected date from the calendar. Note that we are not using any Click event of the button here to read and display the selected date. To trigger the event we are using String Variable trace method to monitor the change in value.

get_date() : Returns us the date as string ( We can't format this, check below selection_get() )
import tkinter as tk
from tkcalendar import Calendar

my_w = tk.Tk()  # Parent window
my_w.geometry("380x200")  # width and height of the window

sel = tk.StringVar(value='02/11/2024')  # connected to Calendar below

cal = Calendar(my_w, selectmode='day', textvariable=sel)
cal.grid(row=1, column=1, padx=20)

def my_upd(*args):  # triggered when the value of the string variable changes
    l1.config(text=cal.get_date())  # read and display date

l1 = tk.Label(my_w, bg='yellow')  # Label to display date
l1.grid(row=1, column=2)

sel.trace_add('write', my_upd) # trigger on change of calendar
my_w.mainloop()  # Keep the window open

Reading Selected date on Button Click

Once the button ( b1) is clicked the function my_upd() is executed and the Label text option is updated with new selection by config() method.
tkcalendar get_date() on button click
import tkinter  as tk 
from tkcalendar import Calendar 
my_w = tk.Tk()
my_w.geometry("380x220")  # width and height of window

cal=Calendar(my_w,selectmode='day') # calendar with default date
cal.grid(row=1,column=1,padx=20)

def my_upd(): # triggered on Button Click
    l1.config(text=cal.get_date()) # read and display date

l1=tk.Label(my_w,bg='yellow')  # Label to display date 
l1.grid(row=1,column=2)

b1=tk.Button(my_w,text='Read',command=lambda:my_upd())
b1.grid(row=2,column=1)
my_w.mainloop()

setting the selected value using selection_set()

We can set the default or change the selection of date to any value by using selection_set(). Input should be as datetime.date or as calendar local.
import tkinter  as tk 
from tkcalendar import Calendar
from  datetime import date
my_w = tk.Tk()
my_w.geometry("380x220")  

cal=Calendar(my_w,selectmode='day')
cal.grid(row=1,column=1,padx=15)

#dt=date(2021,8,19) # specific date Year, month , day
#cal.selection_set(dt) # Set the selected date 
cal.selection_set('8/16/2021') # Set the local calendar format
my_w.mainloop()

Changing the date format

To change the return date format we will use selection_get(), the selection_get() method return the selected date as a datetime.date instance. So we can change the format by using strftime().
In above code the changes inside the function my_upd() is here.
def my_upd(): # triggered on Button Click
    dt=cal.selection_get()
    str=dt.strftime("%d-%m-%Y") # format changed 
    l1.config(text=str) # read and display date
tkcalendar date format
str=dt.strftime("%d-%B-%Y") # format changed

Displaying and Tracking Month and Year with TkCalendar


Event to get Month and Year from currently displayed Calendar using Tkinter TkCalendar in Python


Tkinter's tkcalendar module provides a powerful interface for working with calendar widgets in Python applications. In addition to displaying dates, it supports dynamic updates for the currently displayed month and year. The following code demonstrates how to capture the month and year whenever they change, as well as displaying the information prominently below the calendar.


Event to collect Month & Year of the Calendar

This feature is particularly useful for applications such as scheduling, reporting, or attendance management systems that depend on date-driven functionality.


# Importing required modules
import tkinter as tk
from tkcalendar import Calendar

def update_month_year_display(event=None):
    # Retrieve the calendar widget
    month, year = cal.get_displayed_month()
    formatted_month = f"{month:02}"
    print(f"Month={formatted_month}, Year={year}")
    # Update the label with month and year
    month_year_label.config(text=f"Month={formatted_month}, Year={year}")

# Setting up the main application window
root = tk.Tk()
root.title("Calendar Month/Year Display")

# Configure grid layout
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.rowconfigure(1, weight=0)

# Adding the Calendar widget
cal = Calendar(root)
cal.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")

# Adding a Label to display the current month and year
month_year_label = tk.Label(root, text="", font=("Arial", 16), fg="blue")
month_year_label.grid(row=1, column=0, padx=10, pady=10, sticky="n")

# Bind the CalendarMonthChanged event to the callback
cal.bind("<<CalendarMonthChanged>>", update_month_year_display)

# Initialize display with the current month and year
update_month_year_display()

# Start the Tkinter main loop
root.mainloop()

Explanation

  • Dynamic Initialization: The function update_month_year_display is called during startup to ensure the initial month and year are displayed correctly.
  • Event Binding: The <<CalendarMonthChanged>> event is bound to the callback function, ensuring dynamic updates whenever the calendar's displayed month changes.
  • Grid Layout: The calendar and label are arranged using the grid layout, ensuring a responsive and well-structured UI.
  • Formatted Output: The month is displayed in two digits (e.g., 02 for February) for consistency.

This implementation showcases a polished approach to integrating tkcalendar's dynamic features into a Tkinter application. The real-time updates and intuitive layout make it ideal for date-centric applications like scheduling and data visualization tools.

Managing style and color

Tkcalendar color & style
import tkinter as tk
from tkcalendar import Calendar

# Create the main window
my_w = tk.Tk() # parent window
my_w.geometry("400x300") # width and height
my_w.title("plus2net Customized Calendar")

# Create a Calendar with customized colors directly applied
cal = Calendar(
    my_w,
    selectmode="day",
    year=2024,
    month=11,
    day=2,
    background="#e0f7fa",           # Light cyan background
    foreground="#000000",           # Black text for days
    headersbackground="#004d40",    # Dark teal for headers
    headersforeground="#ffffff",    # White text on headers
    selectbackground="#00796b",     # Teal background for selected date
    selectforeground="#ffffff",     # White text on selected date
    normalbackground="#b2dfdb",     # Light teal for regular days
    normalforeground="#000000"      # Black text on normal days
)
cal.pack(padx=20, pady=20)

# Run the application
my_w.mainloop() # Keep the window open

Creating a Customized Tkinter Calendar with Date Range Restrictions

Tkcalendar mindate and maxdate options for date range selection
The calendar is customized with specific colors and fonts, and it restricts date selection to a defined range between November 13, 2024, and December 25, 2024. Users can interact with the calendar within this specified date range, enhancing the user experience with a visually appealing and functional interface.
import tkinter as tk
from tkcalendar import Calendar
from datetime import date

# Initialize the main window
my_w = tk.Tk()
my_w.title("Customized Calendar with Date Range")
my_w.geometry("400x400") # width and height of the window

# Define minimum and maximum selectable dates
min_date = date(2024, 11, 13) # Year, Month, Day
max_date = date(2024, 12, 25) # Year, Month, Day

# Create and configure the Calendar widget
cal = Calendar(
    my_w,
    selectmode='day',
    year=2024,
    month=11,
    day=6,
    mindate=min_date,
    maxdate=max_date,
    background='lightblue',           # Background color of the calendar
    foreground='black',               # Color of the text for days
    headersbackground='navy',         # Background color of the day headers
    headersforeground='white',        # Text color of the day headers
    selectbackground='green',         # Background color of the selected day
    selectforeground='white',         # Text color of the selected day
    normalbackground='white',         # Background color of normal days
    normalforeground='black',         # Text color of normal days
    weekendbackground='lightgray',    # Background color of weekend days
    weekendforeground='black',        # Text color of weekend days
    othermonthbackground='lightyellow', # Background color of days from other months
    othermonthforeground='gray',      # Text color of days from other months
    bordercolor='black',              # Border color of the calendar
    disableddaybackground='lightgray', # Background color of disabled days
    disableddayforeground='darkgray', # Text color of disabled days
    tooltipbackground='yellow',       # Background color of the tooltip
    tooltipforeground='black',        # Text color of the tooltip
    font=('Arial', 12),               # Font for the calendar
    headersfont=('Arial', 12, 'bold') # Font for the headers
)
cal.pack(padx=20, pady=20)
my_w.mainloop() # Keep the window open

Highlighting Specific Dates in a Tkinter Calendar

Highlighting Holidays in Tkcalendar

The script customizes the calendar's appearance and marks holidays with distinct colors for easy identification.
import tkinter as tk
from tkcalendar import Calendar
from datetime import date

# Initialize the main window
my_w = tk.Tk()
my_w.title("Calendar with Highlighted Holidays")
my_w.geometry("400x400")  # Width and height of the window

# Create and configure the Calendar widget
cal = Calendar(
    my_w,
    selectmode='day',
    year=2024,
    month=11,
    day=1,
    background='white',           # Background color of the calendar
    foreground='black',           # Color of the text for days
    headersbackground='gray',     # Background color of the day headers
    headersforeground='white',    # Text color of the day headers
    selectbackground='blue',      # Background color of the selected day
    selectforeground='white',     # Text color of the selected day
    normalbackground='white',     # Background color of normal days
    normalforeground='black',     # Text color of normal days
    weekendbackground='lightgray',# Background color of weekend days
    weekendforeground='black',    # Text color of weekend days
    othermonthbackground='lightyellow', # Background color of days from other months
    othermonthforeground='gray',  # Text color of days from other months
    bordercolor='black',          # Border color of the calendar
    disableddaybackground='lightgray', # Background color of disabled days
    disableddayforeground='darkgray',  # Text color of disabled days
    tooltipbackground='yellow',   # Background color of the tooltip
    tooltipforeground='black',    # Text color of the tooltip
    font=('Arial', 12),           # Font for the calendar
    headersfont=('Arial', 12, 'bold') # Font for the headers
)
cal.pack(padx=20, pady=20)

# Define holidays to be highlighted
holidays = {
    date(2024, 11, 13): "Diwali",
    date(2024, 12, 25): "Christmas",
    date(2024, 1, 1): "New Year's Day"
}

# Add tags for holidays
for holiday_date, holiday_name in holidays.items():
    cal.calevent_create(holiday_date, holiday_name, 'holiday')

# Configure the 'holiday' tag with a specific background and foreground color
cal.tag_config('holiday', background='red', foreground='white')
my_w.mainloop() # Keep the window open 



Calendar Object Attributes and Methods

Standard Options

  • borderwidth: Sets the width of the border around the calendar.
  • cursor: Sets the cursor to display when the pointer is in the widget.
  • font: Sets the font of the calendar.
  • state: Sets the state of the widget to "normal" or "disabled".

Widget-Specific Options

  • year, month, day: Set the initially displayed year, month, and selected day.
  • firstweekday: Sets the first day of the week to "monday" or "sunday".
  • weekenddays: Sets which days are displayed as weekend days.
  • mindate, maxdate: Set the minimum and maximum allowed dates.
  • showweeknumbers: Determines whether to display week numbers.
  • showothermonthdays: Determines whether to display days from the previous and next months.
  • locale: Sets the locale to use for displaying dates.
  • date_pattern: Sets the pattern used to format the date as a string.
  • selectmode: Sets whether the user can select a day with a mouse click.
  • textvariable: Connects the currently selected date to a variable.

Style Options

  • background, foreground: Sets the background and foreground colors of the calendar.
  • disabledbackground, disabledforeground: Sets the background and foreground colors of the calendar when it is disabled.
  • bordercolor: Sets the color of the day border.
  • headersbackground, headersforeground: Sets the colors for the day names and week numbers.
  • selectbackground, selectforeground: Sets the colors of the selected day.
  • disabledselectbackground, disabledselectforeground: Sets the colors of a selected day when the calendar is disabled.
  • normalbackground, normalforeground: Sets the colors for normal weekdays.
  • weekendbackground, weekendforeground: Sets the colors for weekend days.
  • othermonthforeground, othermonthbackground, othermonthweforeground, othermonthwebackground: Sets colors for days belonging to the previous or next month.
  • disableddaybackground, disableddayforeground: Sets the colors for days when the calendar is disabled.

Tooltip Options (for calevents)

  • tooltipforeground: Sets the color of the tooltip text.
  • tooltipbackground: Sets the background color of the tooltip.
  • tooltipalpha: Sets the opacity of tooltips (between 0 and 1).
  • tooltipdelay: Sets the delay before the tooltip is displayed (in milliseconds).

Methods for Calendar Events

  • calevent_create(date, text, tags=[]): Adds a new event to the calendar.
  • calevent_configure(ev_id, **kw): Configures an existing event.
  • calevent_cget(ev_id, option): Returns the value of a given option for an event.
  • calevent_lower(ev_id, below=None): Lowers an event in the tooltip list.
  • calevent_raise(ev_id, above=None): Raises an event in the tooltip list.
  • calevent_remove(*ev_ids, **kw): Removes events from the calendar.
  • get_calevents(date=None, tag=None): Returns event IDs based on date, tag, or both.

General Methods

  • configure(cnf={}, **kw): Configures widget resources.
  • format_date(date=None): Converts a date object to a string.
  • get_date(): Returns the selected date as a string.
  • get_displayed_month(): Returns the currently displayed month as a tuple (month, year).
  • keys(): Returns a list of all resource names for the widget.
  • see(date): Displays the month in which the given date is located.
  • selection_clear(): Clears the selection.
  • selection_get(): Returns the currently selected date.
  • selection_set(date): Sets the selection to the given date.

Tag Methods

  • tag_cget(tag, option): Returns the value of a tag's option.
  • tag_config(tag, **kw): Configures a tag.
  • tag_delete(tag): Deletes a given tag.
  • tag_names(): Returns a tuple of existing tags.

Virtual Events

  • <<CalendarSelected>>: Generated when the user selects a day with the mouse.
  • <<CalendarMonthChanged>>: Generated when the user changes the displayed month.


Read the list of formats used in displaying Date & time
Calendar mindate & maxdate DateEntry Task list with DateEntry
Projects in Tkinter
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer