1

I'm trying to make a tkinter app where the user can select a date range. The Tkcalendar library only allows to select 1 day, is there a way to select multiple continuous days?

Thank you very much

1 Answers1

1

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
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
  • You could do `dates = [start + timedelta(days=i) for i in range(diff+1)]` instead of `dates = []` + for loop. Secondly there is an indentation issue `date_range()` after the if and there is a `first` instead of `start` in the first `date_range()`. Finally I disagree with the explanation "+1 because range starts from 0": this has nothing to do with `range`, it is a common math problem when you count "ticks" in an interval and want to include both ends. – j_4321 Mar 08 '21 at 16:33
  • 1
    @j_4321 Yes you are correct, I could use an LC but I wanted the OP to understand what is going on. I totally misread the +1, thanks for noticing that. Well since each block in python can have its own indentation level, its not wrong, but it was meant to be 4 spaces. Fixed, thanks :D – Delrius Euphoria Mar 08 '21 at 16:44