Skip to content Skip to sidebar Skip to footer

Can't Load Calendar With Corresponding Date

from tkinter import * from tkcalendar import Calendar def get_date(): label.configure(text=str(today.get_displayed_month())) today.configure(day=str(today.get_date()))

Solution 1:

The error is because day option is only available when you create the Calendar instance. It is not available in configure() function.

If you want to update the label whenever month is changed, you can bind on <<CalendarMonthChanged>> event and update the label inside the event callback:

def on_month_changed(event):
    month, year = today.get_displayed_month()
    label.configure(text=today._month_names[month]+' '+str(year))

...

today = Calendar(win, selectmode='day', year=2020, month=8, day=6)
today.pack(pady=10)
today.bind('<<CalendarMonthChanged>>', on_month_changed)

UPDATE: If you want to select the same day after the month is changed, modify the get_date() function as below:

import calendar
...
def get_date():
    month, year = today.get_displayed_month()
    # get the last day of selected month
    _, lastday = calendar.monthrange(year, month)
    # make sure day is valid day in selected month
    day = min(today._sel_date.day, lastday)
    # select the day in selected month
    today.selection_set(today.date(year, month, day))

UPDATE 2: Below is an example to update the calendar when a date is selected via tkcalendar.DateEntry:

from tkinter import *
from tkcalendar import Calendar, DateEntry

def date_selected(event):
    date = date_entry.get_date()
    cal.selection_set(date)
 
win = Tk()
win.title('Calendar Picker')

date_entry = DateEntry(win, date_pattern='y-mm-dd', state='readonly')
date_entry.pack()
date_entry.bind('<<DateEntrySelected>>', date_selected)

cal = Calendar(win, selectmode='day', date_pattern='y-mm-dd')
cal.pack(pady=10)

win.mainloop()

Post a Comment for "Can't Load Calendar With Corresponding Date"