[Python] Why is the current date number not showing on a tkcalendar restricted to only select...

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have created a tkcalendar to restrict the user by only enabling the selection of Mondays. (The code is based on code previously submitted by j_4321 that allowed the selection of Wednesdays and Fridays.) When the tkcalendar is displayed, the default current date box is empty (no day of month number). If I click on a Monday date (the only selection possible) the selection is highlighted and the current date box now shows the correct number.

    How can I make that current date box show the correct number when the tkcalender first opens. Also, is it possible for the current date number to show as a bold font (and continue to show as bold no matter what other selection the user clicks on)?

    Here is my adapted version of the code and the tkcalendar that opens, followed by the tkcalendar that shows after a Monday is selected.

    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)
    print("sel_date: ", sel_date)
    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[j].state(['disabled'])

    root = tk.Tk()
    root.title("Select a Monday date:")
    # I had to select TUESDAY instead of MONDAY because I reordered the weeks starting on Sun instead of Mon
    cal = MyCalendar(root, firstweekday='sunday', allowed_weekdays=(calendar.TUESDAY,), selectmode='day', locale='en_US',
    font='Arial 14', showweeknumbers=False, showothermonthdays = False, weekendbackground='white',
    weekendforeground='black', othermonthbackground='gray95', othermonthwebackground='gray95',
    othermonthforeground='black', othermonthweforeground='black')
    cal.pack()

    root.mainloop()


    tkcalendar1

    tkcalendar2

    Continue reading...

Compartilhe esta Página