我正在制作一个倒计时日历,用于检查剩余天数、名称和信息,但如果超过 50 天的部分不起作用,则更改颜色的条件是。大家可以查一下吗?它检查每个节日还剩多少。同样如您所见,如果我将日期更改为任何节日的今天,它会显示 1 Day left until
。我想解决这个问题
这是来自festivals.txt
Dashain,14/10/21,This is Nepal Main Festival
Tihar,6/11/21,Festival of Lights
Christmas,25/12/21,Jingle Bells
New Year,1/01/22,The Day of the new year
from tkinter import Tk, Canvas, simpledialog, messagebox
from datetime import date, datetime
# function get_events is to get the celebration events
def get_events():
list_events = []
with open('festivals.txt') as file:
for line in file:
line1 = line.rstrip('\n')
global current_event
current_event = line1.split(',')
current_event[1] = datetime.strptime(current_event[1], '%d/%m/%y').date()
list_events.append(current_event)
return list_events
# Function to get the dates between the 2
def days_between_dates(date1, date2):
time_between = str(date1 - date2)
number_of_days = time_between.split(' ')
return number_of_days[0]
# End of Functions
# -----------------------------------------------------------------------------------------------
# Main program starts here
root = Tk()
root.title('Calendar')
# Make Canvas
c = Canvas(root, width=2000, height=800, bg='black')
c.pack()
c.create_text(100, 50, anchor='w', fill='cyan', font=' Times 40 bold italic underline',
text='My Countdown Calendar' )
# Store the functions in variables
events = get_events()
today = date.today()
# Aligning the text, sorting the list
vertical_space = 100
events.sort(key=lambda x: x[1])
horizontal_space = 100
# Main Loop
for event in events:
event_name = event[0]
days_until = days_between_dates(event[1], today)
display = 'It is %s days until %s. %s is about %s' % (days_until, event_name, event_name,event[2])
if (int(days_until) > 10):
text_col = '#c11a2b'
remin = 'Come one %s in coming' % (event_name)
c.create_text(550, 500, anchor='w', fill='purple', font='Courier 20 bold underline', text=remin)
else:
text_col = 'lime'
c.create_text(200, vertical_space, anchor='w', fill=text_col,
font='Calibri 28 bold', text=display)
vertical_space = vertical_space + 30
horizontal_space = horizontal_space + 40
答案 0 :(得分:0)
日期计算存在一些问题。
首先,您可以使用days
中timedelta
返回的date1 - date2
对象的days_between_dates()
属性获取天数。该函数可以写成:
def days_between_dates(date1, date2):
return (date1 - date2).days
这更简洁且不易出错,现在它将返回一个在其他计算中更有用的整数。
这也修复了一个错误。当日期相同且 str(date1 - date2)
返回时
'0:00:00'
您的代码无法解析。
关于大于 50 的条件,您的代码中没有此类检查。有 > 10
但您的测试数据未测试该条件。您应该在当前日期的 10 天内添加一行日期。
最后,当事件已经发生时,您将需要处理过去的事件。目前,固定代码会显示事件发生前的负天数。