How can we restrict future date selection from tkCalender Date Entry picker in Python?
For tkcalendar >= 1.5.0 it is now possible to restrict the range of available dates with the mindate
and maxdate
options. So the following code prevent the user from selecting future dates:
from tkcalendar import DateEntryfrom datetime import dateimport tkinter as tktoday = date.today()root = tk.Tk()d = DateEntry(root, maxdate=today)d.pack()root.mainloop()
You can use the set_date
method from DateEntry
combined with root.after()
to control the user input.
import tkinter as tkfrom tkcalendar import DateEntryfrom datetime import datetimefrom tkinter import messageboxroot = 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()