0

我正在制作一个日历,我想通过仅启用例如星期一的选择来限制用户。可能吗?我在 tkcalendar 文档中找不到类似的东西。

4

1 回答 1

0

tkcalendar.Calendar具有当一天被“禁用”(每一天是一个ttk.Label)时,它不能被选中并且具有灰色外观的特性。这用于实现日期范围,但可以对其进行调整以仅允许某些工作日。

这个想法是创建一个继承自Calendar并修改_display_calendar()方法以禁用不允许的工作日的类:

import tkinter as tk
import tkcalendar as tkc
import calendar


class MyCalendar(tkc.Calendar):
    def __init__(self, master=None, allowed_weekdays=(calendar.MONDAY,), **kw):
        self._select_only = allowed_weekdays
        tkc.Calendar.__init__(self, master, **kw)
        # change initially selected day if not right day
        if self._sel_date and not (self._sel_date.isoweekday() - 1) in allowed_weekdays:
            year, week, wday = self._sel_date.isocalendar()
            # get closest weekday
            next_wday = max(allowed_weekdays, key=lambda d: (d - wday + 1) > 0) + 1
            sel_date = self.date.fromisocalendar(year, week + int(next_wday < wday), next_wday)
            self.selection_set(sel_date)

    def _display_calendar(self):
        # display calendar
        tkc.Calendar._display_calendar(self)
        # disable not allowed days
        for i in range(6):
            for j in range(7):
                if j in self._select_only:
                    continue
                self._calendar[i][j].state(['disabled'])


root = tk.Tk()
cal = MyCalendar(root, allowed_weekdays=(calendar.WEDNESDAY, calendar.SATURDAY),
                 weekendbackground='white', weekendforeground='black',
                 othermonthbackground='gray95', othermonthwebackground='gray95',
                 othermonthforeground='black', othermonthweforeground='black')
cal.pack()
root.mainloop() 

截屏

于 2021-02-25T09:32:29.403 回答