索引错误,倒计时日历不工作



你能帮我写代码吗?

我想要一个if-else语句,如果没有给出节日的描述,它显示没有关于该特定节日的信息。这里,我要用if not(event[2])但是这里,显示的是

Traceback (most recent call last):
File "C:Userskanav_i4cko4cDownloadsMy first tkinter program.py", line 52, in <module>
if (event[2]):
IndexError: list index out of range

这是festivals.txt的源代码

Diwali,5/11/21
Christmas,25/12/21

这是主程序的源代码

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(',')
print('Check 0')
print(current_event)
current_event[1] = datetime.strptime(current_event[1], '%d/%m/%y').date()
list_events.append(current_event)
return list_events

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')
c = Canvas(root, width=2000, height=800, bg='dark blue')
c.pack()
c.create_text(100, 50, anchor='w', fill='white', font=' Times 40 bold underline',
text='My Countdown Calendar')
c.create_rectangle(30, 10, 60, 1000,
outline="#fb0", fill="#fb0")
events = get_events()
today = date.today()
# Make a dictionary for the festivals

vertical_space = 100
events.sort(key=lambda x: x[1])
horizontal_space = 100
for event in events:
event_name = event[0]
days_until = days_between_dates(event[1], today)
if (event[2]):
display = 'It is %s days until %s. %s =  %s' % (days_until, event_name, event_name,event[2])
else:
display = 'It is %s days until %s. There is no info on %s' % (days_until, event_name, event_name)
if (int(days_until) <= 50):
text_col = '#c11a2b'
else:
text_col = 'SkyBlue1'
c.create_text(100, vertical_space, anchor='w', fill=text_col,
font='Calibri 28 bold', text=display)
vertical_space = vertical_space + 30
horizontal_space = horizontal_space + 40

当你计算event[2]时,它试图检索列表中不存在的第3项,因此python引发异常。

一个解决方案是用默认值初始化列表:

event = [None for i in range(3)]

这样,在event[2]处有一个None值,可以通过if语句求值。

另一个解决方案是简单地检查列表是否包含少于3个项目:

if len(event) <= 2:
# do something

相关内容

  • 没有找到相关文章

最新更新