2

I am creating a graphic user application in Python using tkinter. For date picker I am using Date Entry from tkCalendar for this purpose. The requirement is to restrict user from selecting future dates. How can I achieve that in this case?

Python version 3.7

tkCalendar version 1.3.1

j_4321
  • 15,431
  • 3
  • 34
  • 61
Saurav Kumar
  • 61
  • 1
  • 4

2 Answers2

3

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 DateEntry
from datetime import date
import tkinter as tk
today = date.today()
root = tk.Tk()
d = DateEntry(root, maxdate=today)
d.pack()
root.mainloop()
j_4321
  • 15,431
  • 3
  • 34
  • 61
1

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()
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • This isn't an ideal solution!! the best solution is to listen for changes on the widget itself. UPDATE!!!: For newer versions you can restrict the range using mindate and maxdate – Jamal Alkelani Jul 26 '21 at 22:08