create a tkinter window with a calendar in python

To create a tkinter window with a calendar in Python, you can use the built-in calendar module and the tkinter module. Here's an example code:

main.py
import calendar
import tkinter as tk
import datetime

class Calendar:
    def __init__(self, parent, values):
        self.values = values
        self.parent = parent
        self.cal = calendar.monthcalendar(datetime.date.today().year, datetime.date.today().month)

        self._setup_styles()
        self._build_calendar()

    def _setup_styles(self):
        style = tk.Style(self.parent)
        style.theme_use('default')
        style.configure("Treeview",
            background="white",
            foreground="black",
            rowheight=25,
            fieldbackground="white"
        )
        style.configure("Treeview.Heading", font=("Calibri", 10, 'bold'))

    def _build_calendar(self):
        for i in self.values.get_children():
            self.values.delete(i)
        year, month = datetime.date.today().year, datetime.date.today().month
        header = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        for day in header:
            self.values.insert('', 'end', text=day)
        for week in self.cal:
            if week[0] == 0:
                self.values.insert('', 'end', text=' ')
            else:
                values = [day if day != 0 else '' for day in week]
                self.values.insert('', 'end', values=values)

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Calendar")
    values = tk.Treeview(root, columns=tuple(range(7)), show="headings")
    for col in range(7):
        values.heading(col, text=str(col))
    values.pack(side="left", fill="both", expand=True)
    cal = Calendar(root, values=values)
    root.mainloop()

1604 chars
49 lines

This code creates a window with a calendar widget that shows the current month. You can navigate to other months using the control buttons on the widget. You can also customize the appearance and functionality of the widget to suit your needs.

gistlibby LogSnag