Create a date picker calendar in Python Tkinter

There are many libraries in Python which provide Graphic User Interface(GUI) features like PyQt5, Kivv, Tkinter, etc… Among these Tkinter is the most commonly¬†used library for GUI. In this tutorial, we will develop a date picker using Tkinter.

How to create a date picker calendar using the Tkinter Python package?

There is no direct in-built function in the Tkinter package for the date picker. First, we create a calendar using tkcalendar module. tkcalendar provides some useful features like get_date(). These functions help us to get the clicked date into an object which we can display. To use tkcalendar first we have to install tkcalendar from the terminal using this command.

pip install tkcalendar

What is PIP in Python?  This explains what is PIP.

After installing tkcalendar we follow these steps to create a date picker.

  1. Create a Tkinter object with a window size using Tk().
  2. create a calendar object. Display this object in the Tkinter window.
  3. Create a function to fetch date from the calendar and write it in an object.
  4. Fetch on the clicking the button and display it on screen.

Now we implement these steps using python.

Code:

from tkinter import *
from tkcalendar import Calendar

# creating an object of tkinter

tkobj = Tk()

# setting up the geomentry

tkobj.geometry("400x400")
tkobj.title("Calendar picker")
#creating a calender object

tkc = Calendar(tkobj,selectmode = "day",year=2022,month=1,date=1)

#display on main window
tkc.pack(pady=40)

# getting date from the calendar 

def fetch_date():
    date.config(text = "Selected Date is: " + tkc.get_date())

#add button to load the date clicked on calendar

but = Button(tkobj,text="Select Date",command=fetch_date, bg="black", fg='white')
#displaying button on the main display
but.pack()
#Label for showing date on main display
date = Label(tkobj,text="",bg='black',fg='white')
date.pack(pady=20)
#starting the object
tkobj.mainloop()

Output:

 

Leave a Reply

Your email address will not be published. Required fields are marked *