from Tkinter import * import time DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] MONTHS = [' ', # Placeholder so we can index from 1 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] LENGTHS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] class Calendar: def __init__(self, master): self.master = master self.create_widgets() self.fill() def create_widgets(self): self.topframe = Frame(self.master) self.topframe.pack(fill=X, side=TOP) self.prevyearbutton = Button(self.topframe, text="<<", command=self.prevyear) self.prevyearbutton.pack(side=LEFT) self.prevbutton = Button(self.topframe, text="<", command=self.prev) self.prevbutton.pack(side=LEFT) self.nextyearbutton = Button(self.topframe, text=">>", command=self.nextyear) self.nextyearbutton.pack(side=RIGHT) self.nextbutton = Button(self.topframe, text=">", command=self.next) self.nextbutton.pack(side=RIGHT) self.toplabel = Button(self.topframe, relief=FLAT, command=self.reset) self.toplabel.pack(expand=1, fill=X) self.midframe = Frame(self.master) self.midframe.pack(expand=1, fill=BOTH, side=TOP) self.columns = [] for i in range(7): column = Frame(self.midframe) column.pack(side=LEFT, expand=1, fill=BOTH) dayname = Label(column, text=DAYS[i]) dayname.pack(side=TOP, fill=X) daybuttons = [] for j in range(6): daybutton = Button(column) daybutton.pack(side=TOP, fill=X) daybuttons.append(daybutton) self.columns.append(daybuttons) def fill(self, year=0, month=0): now = time.time() today = time.localtime(now) t = time.mktime((year or today[0], month or today[1], 1) + 6*(0,)) date = time.localtime(t) year, month, day, hh, mm, ss, weekday, yearday, isdst = date self.year, self.month = year, month label = "%s %d" % (MONTHS[month], year) self.toplabel.config(text=label) maxdate = LENGTHS[month] if month==2 and year%4 == 0 and (year%400 == 0 or year%100 != 0): maxdate = 29 # weekday encoding: Monday=0, ..., Sunday=6 weekday1 = (weekday - (day-1)) % 7 # First of the month weekday0 = (weekday1+1) % 7 # Sunday=0, ..., Saturday=6 here = -weekday0 bg = self.midframe['background'] for row in range(6): for col in range(7): daybutton = self.columns[col][row] here = here+1 if 1 <= here <= maxdate: if here == today[2] and date[:2] == today[:2]: bgcolor = "green" else: bgcolor = bg daybutton.config(text="%d" % here, state=NORMAL, relief=RAISED, background=bgcolor) else: daybutton.config(text="", state=DISABLED, relief=FLAT, background=bg) def prevyear(self): self.fill(self.year-1, self.month) def prev(self): year, month = self.year, self.month-1 if month < 1: year, month = year-1, 12 self.fill(year, month) def next(self): year, month = self.year, self.month+1 if month > 12: year, month = year+1, 1 self.fill(year, month) def nextyear(self): self.fill(self.year+1, self.month) def reset(self): self.fill()