【问题标题】:Having the error "IndexError: list index out of range" in working with python, tkinter在使用 python、tkinter 时出现错误“IndexError: list index out of range”
【发布时间】:2021-09-23 11:20:38
【问题描述】:

我是 python 新手,我想知道为什么我的程序不工作。第 23 行的错误是“IndexError: list index out of range” (这个节目是为明天我最好朋友的生日准备的)

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

【问题讨论】:

    标签: python list datetime tkinter indexing


    【解决方案1】:

    你的代码有两个问题:

    • 在执行b_date.get().split( '-' ) 时,尚未输入任何文本,因此您总是得到一个空字符串,从这里IndexError
    • b_datename 都在第 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 中将事件绑定到函数,例如this answer
    • 像往常一样拆分字符串
    • 您确保仅在字符串与给定格式匹配时继续您的详细说明。简单的方法:确保至少有两个“-”字符。最佳方法:检查字符串格式是否为“yyyy-mm-dd”
    • 请注意,您还打印了name。你应该打印name.get()。此外,您正在控制台上打印它,而您可能对updating a label in tkinter 感兴趣

    祝你的朋友好运,生日快乐

    【讨论】:

      【解决方案2】:

      所以在你程序的这一行:b_date = b_date.get().split( '-' ) 你的 GUI 没有运行,所以b_date 可能是一个空列表。

      您可能需要添加Button 来触发执行此拆分和测试的代码。

      另请注意,任何print() 函数都将打印到终端而不是 GUI。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-03
        • 2018-02-08
        • 2014-10-20
        • 2019-02-23
        相关资源
        最近更新 更多