我正在嘗試創建一個 Tkinter 應用程式,其中用戶在日歷中選擇一個日期,然后按 abutton和 alabel然后顯示當前日期和他們選擇的日期之間的天數。我已經想出了如何計算 2 個設定日期之間的天數,但是當我引入日歷時,它說的是日期,does not match format '%m/%d/%Y'因為日歷將日期的年份設定為 21 而不是 2021 例如12/9/21。任何解決方案將不勝感激。
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()
uj5u.com熱心網友回復:
添加date_pattern="m/d/y"到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)
您還需要在里面獲取選定的日期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()
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313682.html
