Python Calendar

by Alex
Python Calendar

One of the first programs you can try in Python is a calendar. It is not hard, but it is a good way to train your skills with the standard Tkinter and calendar libraries.

Program description

The calendar is written in Python 3 using the Tkinter graphical library. The standard calendar library was used to determine the current day of the week and the number of days in the month. We will display the calendar for the current month as a table. The current date will be highlighted in green. We will also add buttons to flip through the months.
Program description

Connecting libraries and declaring variables

Include the standard libraries Tkinter, datetime, and calendar with import. Initialize the root class that will be used to draw the graphical interface. Specify the “Calendar” window title. Declare an empty list of days. In the future, it will store the fields of the table. Each field corresponds to a certain day. In the variable now we will store the current date. Variables year and month will store the year and month, which calendar is currently displayed.

from tkinter import *
import calendar
import datetime
root = Tk()
days = []
now =
year = now.year
month = now.month

Change the current month

The prew and next functions will be called when one of the month change keys is pressed. If the current month is “January” and the user presses the change to the previous month button, the year will be decremented and the month will change to “December”. Note that the month and year variables are global. Therefore, you must use the keyword global before changing their values in the function. The fill function redraws the calendar.

def prew():
    global month, year
    month -= 1
    if month == 0:
        month = 12
        year -= 1

def next():
    global month, year
    month += 1
    if month == 13:
        month = 1
        year += 1

Redrawing the calendar

The fill function will redraw the display of all items. It will be called at the beginning of the program, and every time the month for which you want to display the calendar changes. First, we output the name of the month and the year. We calculate the number of days in previous month and write it into prew_month_days variable. In the variable week_day we write the number of day of the week of the first day of the month (from 0 – if the first day falls on Monday, to 6 – on Sunday). After that, in three cycles we output the numbers and correct their colors:

  1. In the first cycle, fill in the day numbers of the selected month. We will display them in black. If it is the current day, its background is green.
  2. In the second cycle we fill in the numbers of the previous month. They will be displayed in gray.
  3. In the third loop, we add the next month’s numbers. They are also displayed in gray.
def fill():
    info_label['text'] = calendar.month_name[month] + ', ' + str(year)
    month_days = calendar.monthrange(year, month)[1]
    if month == 1:
        prew_month_days = calendar.monthrange(year-1, 12)[1]
        prew_month_days = calendar.monthrange(year, month - 1)[1]
    week_day = calendar.monthrange(year, month)[0]
    for n in range(month_days):
        days[n + week_day]['text'] = n+1
        days[n + week_day]['fg'] = 'black'
        if year == now.year and month == now.month and n ==
            days[n + week_day]['background'] = 'green'
            days[n + week_day]['background'] = 'lightgray'
    for n in range(week_day):
        days[week_day - n - 1]['text'] = prew_month_days - n
        days[week_day - n - 1]['fg'] = 'gray'
        days[week_day - n - 1]['background'] = '#f3f3f3'
    for n in range(6*7 - month_days - week_day):
        days[week_day + month_days + n]['text'] = n+1
        days[week_day + month_days + n]['fg'] = 'gray'
        days[week_day + month_days + n]['background'] = '#f3f3f3'

Displaying items

To display the calendar in Python 3 we use the Tkinter library. We will use its grid packer. It will present all elements we create as a table. In the first row in the leftmost and rightmost cells (with column numbers 0 and 6) we will display the buttons for changing months. In the center, we will display a text field that will display the current year and month. This field will occupy 5 table cells, so set the columnspan parameter to 5.

prew_button = Button(root, text='<', command=prew)
prew_button.grid(row=0, column=0, sticky='nsew')
next_button = Button(root, text='>', command=next)
next_button.grid(row=0, column=6, sticky='nsew')
info_label = Label(root, text='0', width=1, height=1, 
            font=('Verdana', 16, 'bold'), fg='blue')
info_label.grid(row=0, column=1, columnspan=5, sticky='nsew')

In the second line we display the abbreviated names of the months. Next we will display 6 rows of 7 columns, which we will fill with numbers denoting day numbers. Finally, we use the fill function, which will fill our calendar with the initial data – the calendar of the current month. After that we run the mainloop event loop.

for n in range(7):
    lbl = Label(root, text=calendar.day_abbr[n], width=1, height=1, 
                font=('Verdana', 10, 'normal'), fg='darkblue')
    lbl.grid(row=1, column=n, sticky='nsew')
for row in range(6):
    for col in range(7):
        lbl = Label(root, text='0', width=4, height=2, 
                    font=('Verdana', 16, 'bold'))
        lbl.grid(row=row+2, column=col, sticky='nsew')

The example program in Python 3 to output the calendar using the Tkinter library is quite simple. It will help programmers in learning the language. Here we have different conditional statements and loops, working with global variables in functions. The hardest part of this example is displaying graphical elements. This example can be more complicated and display the calendar for the whole year at once. To do this, you will need to use classes.

Related Posts