0
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()))

 
win = Tk()
win.title('Calendar Picker')

label = Label(win,text='August 2020')
label.pack(pady=10)

btn = Button(win,text='Pick a date',command=get_date)
btn.pack(pady=10)

today = Calendar(win,selectmode='day',year=2020,month=8,day=6)
today.pack(pady=10)

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "E:\Python\Python Projects Fun\calproject.py", line 6, in get_date
    today.configure(day=str(today.get_date()))
  File "C:\Python38\lib\site-packages\tkcalendar\calendar_.py", line 1612, in configure
    self[item] = value
  File "C:\Python38\lib\site-packages\tkcalendar\calendar_.py", line 518, in __setitem__
    raise AttributeError("Calendar object has no attribute %s." % key)
AttributeError: Calendar object has no attribute day.

抱歉,当我按下“选择日期”按钮时,出现了上述错误。请问如果我想在移动月份时在窗口顶部显示相应的日期,我应该使用什么?因为我不清楚文档所以有人可以教我这个方法吗?解决上述错误的最佳方法是什么?

4

1 回答 1

3

该错误是因为day选项仅在您创建Calendar实例时可用。configure()它在功能中不可用。

如果要更新label月份更改时,可以绑定<<CalendarMonthChanged>>事件并更新label事件回调内部:

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)

更新:如果要在更改月份后选择同一天,请修改以下get_date()功能:

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))

更新 2:以下是通过以下方式选择日期时更新日历的示例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()
于 2020-08-06T03:52:35.233 回答