I am trying to create a Tkinter application where the user selects a date in a calendar and then presses a button and a label
then displays the number of days between the current date and the date they have selected. I have figured out how to calculate the number of days between 2 set dates however when I introduced the calendar, it says the date does not match format '%m/%d/%Y'
because the calendar sets the year of the date as 21 instead of 2021 e.g. 12/9/21
. Any solutions would be appreciated.
import datetime
from tkinter import *
from tkcalendar import *
root = Tk()
root.title('Date')
root.geometry("600x400")
from datetime import date
from time import strftime
from datetime import timedelta, datetime, date
from datetime import datetime
def calculate():
delta = b - a
l1 = Label(root, text=delta.days)
l1.pack()
#calendar
cal = Calendar(root, background="#99cbd8", disabledbackground="blue", bordercolor="#99cbd8", headersbackground="light blue", normalbackground="pink", foreground="blue", normalforeground='white', headersforeground='white', selectmode="day", year=2021, month=12, day=9)
cal.pack(pady=20)
plum = datetime.today().strftime("%m/%d/%Y") #getting the current date
pear = cal.get_date() #getting the date from the calendar
date_format = "%m/%d/%Y"
a = datetime.strptime(plum, date_format)
b = datetime.strptime(pear, date_format)
button = Button(root, text="calc", command=calculate)
button.pack()
#delta = b - a
#print(delta.days)
root.mainloop()
CodePudding user response:
Add date_pattern="m/d/y"
to Calender(...)
:
cal = Calendar(root, date_pattern="m/d/y", background="#99cbd8", disabledbackground="blue", bordercolor="#99cbd8", headersbackground="light blue", normalbackground="pink", foreground="blue", normalforeground='white', headersforeground='white', selectmode="day", year=2021, month=12, day=9)
Also you need to get the selected date inside calculate()
:
def calculate():
pear = cal.get_date()
b = datetime.strptime(pear, date_format)
delta = b - a
l1.config(text=delta.days) # update label
...
button = Button(root, text="calc", command=calculate)
button.pack()
# create the label
l1 = Label(root)
l1.pack()
...