我是python的新手,我想知道为什么我的程序不工作。错误是";IndexError:列表索引超出范围";用于第23行(这个节目是为我最好的朋友明天的生日准备的(
import datetime
import tkinter
from tkinter import *
t = Tk()
t.resizable(0, 0)
t.title("Sana's birthday!!!")
t.geometry('200x200')
current_date = datetime.date.today().strftime('%Y-%m-%d')
current_date_lst = current_date.split('-')
l1 = Label(t, text='Sana enter your birthday in yyyy-mm-dd format:').grid(row=1, column=1)
l2 = Label(t, text='Name of your birthday legend?:').grid(row=2, column=1)
b_date = tkinter.Entry(t)
b_date.grid(row=1, column=2)
name = tkinter.Entry(t)
name.grid(row=1, column=2)
b_date = b_date.get().split( '-' )
if current_date_lst[1] == b_date[1] and current_date_lst[2] == b_date[2]:
age = int(current_date_lst[0]) - int(b_date[0])
ordinal_suffix = {1: 'st', 2:'nd', 3:'rd', 11:'th', 12:'th', 13:'th'}.get(age % 10 if not 10<age<=13 else age % 14, 'th')
print(f" It's {name}'s {age}{ordinal_suffix} Birthday!")
else:
print('Sorry, today is not your birthday:(')
mainloop()
错误:
if current_date_lst[1] == b_date[1] and current_date_lst[2] == b_date[2]:
IndexError: list index out of range
您的代码有两个问题:
- 执行
b_date.get().split( '-' )
时,尚未在条目中输入任何文本,因此您总是得到一个空字符串,从这里得到IndexError
b_date
和name
都已经在第1行第2列上网格化。因此,即使你认为你在b_date
条目上写作,你实际上是在name
条目上写作
第二个问题由name.grid(row=2, column=2)
平凡地解决。相反,要解决第一个问题,您需要确保只有在编写了一些文本后才能读取条目。
一种可能的解决方案是:强制用户在输入一些文本后按下按钮。我更喜欢的一种方法是:对于输入的每个字符,检查字符串是否正确,如果正确,就采取措施。
这里有一些示例代码:
import datetime
import tkinter
from tkinter import *
t = Tk()
t.resizable(0, 0)
t.title("Sana's birthday!!!")
t.geometry('200x200')
current_date = datetime.date.today().strftime('%Y-%m-%d')
current_date_lst = current_date.split('-')
l1 = Label(t, text='Sana enter your birthday in yyyy-mm-dd format:').grid(row=1, column=1)
l2 = Label(t, text='Name of your birthday legend?:').grid(row=2, column=1)
b_date = tkinter.Entry(t)
b_date.grid(row=1, column=2)
name = tkinter.Entry(t)
name.grid(row=2, column=2)
t.bind("<KeyRelease>", lambda e: show_string(b_date, name))
def show_string(b_date, name):
b_date = b_date.get().split( '-' )
name = name.get()
if len(b_date)==3:
if current_date_lst[1] == b_date[1] and current_date_lst[2] == b_date[2]:
age = int(current_date_lst[0]) - int(b_date[0])
ordinal_suffix = {1: 'st', 2:'nd', 3:'rd', 11:'th', 12:'th', 13:'th'}.get(age % 10 if not 10<age<=13 else age % 14, 'th')
print(f"It's {name}'s {age}{ordinal_suffix} Birthday!")
else:
print('Sorry, today is not your birthday:(')
mainloop()
正在发生的事情:
- 您按下
bind
键(实际上是释放了键,以确保您正在寻找实际输入的字符串(到检查器函数show_string
。查看如何将事件绑定到tkinter中的函数,例如以下答案 - 你像往常一样把绳子分开
- 您确保只有在字符串与给定格式匹配的情况下才能继续进行精化。琐碎的方法:确保至少有两个"-"字符。最佳方法:检查字符串的格式是否为";yyyy-mm-dd">
- 请注意,您也在打印
name
。您应该打印name.get()
。此外,您正在控制台上打印它,而您可能有兴趣更新tkinter中的标签
祝你的朋友好运,生日快乐
所以在程序的这一行:b_date = b_date.get().split( '-' )
您的GUI没有运行,所以b_date
可能是一个空列表。
您可能需要添加一个Button
来触发执行此拆分和测试的代码。
还要注意,任何print()
功能都将打印到终端,而不是GUI上。