How to Create a Date Picker in Tkinter

Tkinter Date Picker

First you have to install tkcalendar by saying this, in your terminal:

pip install tkcalendar

Here is a simple example on tkcalendars DateEntry:

from tkinter import *
from tkinter import ttk
from tkcalendar import DateEntry

root = Tk()

e7 = DateEntry(root, values="Text", year=2020, state="readonly", date_pattern="yyyy-mm-dd")
e7.grid(row=1, column=1, padx=20, pady=5, sticky=W)

root.mainloop()

You could also use tkcalendars Calendar:

from tkcalendar import Calendar

e7 = Calendar(root, values="Text", year=2020, state="readonly", date_pattern="yyyy-mm-dd")
e7.grid(row=1, column=1, padx=20, pady=5, sticky=W)

For your case, you can use two of any of these widgets to get (e7.selection_get()) the start date and the end date and then work with it.

Here is the documentation for more information on the widget

Hope it cleared your doubts, if you have errors, do let me know

Cheers

Change date format in Tkinter date picker - python

reference:- Python Tkinter Tk Calendar get custom date not working and unable to display date in format: "DD-MM-YYYY"

You could do something like this:-

from tkinter import *
from tkcalendar import *
root=Tk()
root.geometry("500x500")
def mainF():
global cal
def getDate():
date=cal.get_date()
print(date)
cal.pack(pady=20, padx=20)
butt=Button(root,text="Date Getter", bg="cyan",command=getDate).pack()
cal=Calendar(root,selectmode="day",date_pattern="dd-mm-y")
but=Button(root,text="Pick Date",command=mainF).pack()
root.mainloop()

this is a small date picker app, that changes the format to dd-mm-yy instead of mm-dd-yy, you can implement format change in your code like this

Select date range with Tkinter

You can create two calendars and then choose two dates and then find the range between those two dates. The core function would be:

def date_range(start,stop): # Start and stop dates for range
dates = [] # Empty list to return at the end
diff = (stop-start).days # Get the number of days between

for i in range(diff+1): # Loop through the number of days(+1 to include the intervals too)
day = first + timedelta(days=i) # Days in between
dates.append(day) # Add to the list

if dates: # If dates is not an empty list
return dates # Return it
else:
print('Make sure the end date is later than start date') # Print a warning

Now to put things in tkinter perspective, button callbacks cannot return anything, so this should be something like:

from tkinter import *
import tkcalendar
from datetime import timedelta

root = Tk()

def date_range(start,stop):
global dates # If you want to use this outside of functions

dates = []
diff = (stop-start).days
for i in range(diff+1):
day = start + timedelta(days=i)
dates.append(day)
if dates:
print(dates) # Print it, or even make it global to access it outside this
else:
print('Make sure the end date is later than start date')

date1 = tkcalendar.DateEntry(root)
date1.pack(padx=10,pady=10)

date2 = tkcalendar.DateEntry(root)
date2.pack(padx=10,pady=10)

Button(root,text='Find range',command=lambda: date_range(date1.get_date(),date2.get_date())).pack()

root.mainloop()

Keep in mind, the list is full of datetime objects, to make a list full strings of date alone, say:

dates = [x.strftime('%Y-%m-%d') for x in dates] # In the format yyyy-mm-dd

Python Tkinter Tk Calendar get custom date not working and unable to display date in format: "DD-MM-YYYY"

First of all, in

 getdat=Button(calFrame,text="Get This Date",bg="#00ffde", command=getCustomDate())

you are executing the function instead of passing it as an argument, like in Why is the command bound to a Button or event executed when declared?.

Then, according to the docstring of Calendar, it takes a date_pattern option

date_pattern : str
date pattern used to format the date as a string. The default
pattern used is babel's short date format in the Calendar's locale.

A valid pattern is a combination of 'y', 'm' and 'd' separated by
non letter characters to indicate how and in which order the
year, month and day should be displayed.

y: 'yy' for the last two digits of the year, any other number of 'y's for
the full year with an extra padding of zero if it has less
digits than the number of 'y's.
m: 'm' for the month number without padding, 'mm' for a
two-digit month
d: 'd' for the day of month number without padding, 'dd' for a
two-digit day

Examples for datetime.date(2019, 7, 1):

'y-mm-dd' → '2019-07-01'
'm/d/yy' → '7/1/19'

So just pass date_pattern="dd-mm-yyyy" in argument when creating the Calendar.

Here is an example

from tkinter import Tk, Button
from tkcalendar import Calendar

def getCustomDate():
print(cal.get_date())

root = Tk()

cal = Calendar(root,
selectmode="day",
firstweekday="monday",
background="#0f8bff",
foreground="black",
disabledforeground="#a3bec7",
bordercolor="grey",
normalbackground="#d0f4ff",
weekendbackground="#8ffeff",
weekendforeground ="black",
disabledbackground="99b3bc",
date_pattern="dd-mm-yyyy")
cal.pack(pady=10)
getdat=Button(root, text="Get This Date",
bg="#00ffde", command=getCustomDate)
getdat.pack()
root.mainloop()

How can we restrict future date selection from tkCalender Date Entry picker in Python?

You can use the set_date method from DateEntry combined with root.after() to control the user input.

import tkinter as tk
from tkcalendar import DateEntry
from datetime import datetime
from tkinter import messagebox

root = tk.Tk()
time_now = datetime.now()
calendar = DateEntry(root, width=12, background='darkblue',foreground='white', borderwidth=2)
calendar.pack()

def date_check():
calendar_date = datetime.strptime(calendar.get(),"%m/%d/%y")
if calendar_date > time_now:
messagebox.showerror("Error", "Selected date must not exceed current date")
calendar.set_date(time_now)
root.after(100,date_check)

root.after(100,date_check)

root.mainloop()


Related Topics



Leave a reply



Submit