如何解决使用 Tkinter 选择日期范围
我正在尝试制作一个 tkinter 应用程序,用户可以在其中选择日期范围。 tkcalendar库只允许选择1天,有没有办法选择连续的多天?
非常感谢
解决方法
您可以创建两个日历,然后选择两个日期,然后找出这两个日期之间的范围。核心功能是:
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
现在从 tkinter
的角度来看,按钮回调不能return
任何东西,所以这应该是这样的:
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()
请记住,列表中充满了日期时间对象,要单独列出完整的日期字符串,例如:
dates = [x.strftime('%Y-%m-%d') for x in dates] # In the format yyyy-mm-dd
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。