【问题标题】:How to prevent list index out of range in python tkinter如何防止python tkinter中的列表索引超出范围
【发布时间】:2021-04-01 18:51:28
【问题描述】:
from tkinter import 

new_window = Tk()
new_window.title("Writing speed")
new_window.geometry("700x600+300+50")

question = ["How are you",
            "Are you ok",
            "I am fine",
            "Long time no see",
            "Good bye"]

result = []
user_result = []

question_index = 0

def clear(event):
    user_input.delete(0, END)

def skip():
    global question_index
    question_index += 1
    label1.config(text=f"Please write the following words\n\n {question[question_index]}")

def delete():
    user_input.delete(0, END)

def check():
    get_input_from_user = user_input.get()
    user_result.append(get_input_from_user)
    user_input.delete(0, END)
    skip()

label1 = Label(new_window, text="Please write the following words\n\n {}".format(question[question_index]), font=("Arial black", 20))
user_input = Entry(new_window, width=40, font=("Courier New", 20))
skip_button = Button(new_window, text="skip", command=skip, width=40, bg="light green")
check_button = Button(new_window, text="check", command=check, width=40, bg="light green")
delete_button = Button(new_window, text="Delete", fg="red", bg="yellow", command=delete)

user_input.insert(0, "Your text here")
user_input.bind("<Button-1>", clear)
label1.pack()
user_input.pack(padx=20, pady=20)
skip_button.pack(padx=20)
check_button.pack(padx=20, pady=20)
delete_button.pack()
delete_button.place(x=625, y=144)

new_window.mainloop()

question_index = 0
user_result_index = 0

print(user_result)

for i in range(5):
    if user_result[user_result_index] == question[question_index]:
        result.append("Correct")
        question_index += 1
        user_result_index += 1
    else:
        result.append("Incorrect")
        question_index += 1
        user_result_index += 1

print(result)

如果用户按下检查按钮超过5次,代码的输出是索引范围超出范围以及如何防止用户按下检查按钮超过或等于5次。有没有办法解决这个问题,因为我尝试了很多方法来解决它,但都失败了。

欢迎任何评论。

【问题讨论】:

  • 显示您的尝试和回溯

标签: python tkinter


【解决方案1】:

您可以将您的 skip function 更改为此。现在它做了什么我创建了一个skip_counter 变量,它计算如果它大于5,那么它将防止你出错。您的ERROR 实际上基本上意味着您正在尝试访问您的列表超出其size

示例:

>>> mylist = ["How are you",
... "Are you ok",
... "I am fine",
... "Long time no see",
... "Good bye"]
>>> mylist[0]
'How are you'
>>> mylist[1]
'Are you ok'
>>> mylist[2]
'I am fine'
>>> mylist[3]
'Long time no see'
>>> mylist[4]
'Good bye'
>>> mylist[5] #Imagine your question_index variable are the numbers
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

代码解决方案:

question_index = 0
skip_counter = 1

def skip():
    global skip_counter
    skip_counter+=1

    if skip_counter > 5:
        print("Preventing Index out of Bounds Range")
    else:
        global question_index
        print(skip_counter)
        question_index += 1
        label1.config(text=f"Please write the following words\n\n {question[question_index]}")

或者另一种方式是这样,只需检查您的 question_index 变量。

question_index = 0

def skip():
    global question_index
    if question_index > 3:
        print("Preventing Index out of Bounds Range")
    else:
        print(question_index)
        question_index += 1
        label1.config(text=f"Please write the following words\n\n {question[question_index]}")

【讨论】:

    【解决方案2】:

    根据条件尝试按钮启用/禁用:)

    from tkinter import *
    
    fenster = Tk()
    fenster.title("Window")
    
    def switch():
        if b1["state"] == "normal":
            b1["state"] = "disabled"
            b2["text"] = "enable"
        else:
            b1["state"] = "normal"
            b2["text"] = "disable"
    
    #--Buttons
    b1 = Button(fenster, text="Button", height=5, width=7)
    b1.grid(row=0, column=0)    
    
    b2 = Button(text="disable", command=switch)
    b2.grid(row=0, column=1)
    
    fenster.mainloop()
    

    【讨论】:

      【解决方案3】:
      if question_index < 4:
         question_index += 1
      

      尝试为每个增量添加此 if 语句。由于列表问题只有 5 个条目,如果您要求其第六个条目,它会吐出该错误。 (确保您正确缩进增量以属于 if 语句。):)

      【讨论】:

        【解决方案4】:

        请尝试改变

        for i in range(5):
            if user_result[user_result_index] == question[question_index]:
                result.append("Correct")
                question_index += 1
                user_result_index += 1
            else:
                result.append("Incorrect")
                question_index += 1
                user_result_index += 1
        
        print(result)
        

        for i in range(5):
            if user_result[user_result_index] == question[question_index]:
                result.append("Correct")
        if question_index <4:
                question_index += 1
        if user_result_index <4:
                user_result_index += 1
            else:
                result.append("Incorrect")
        if question_index <4:
                question_index += 1
        if user_result_index <4:
                user_result_index += 1
        
        print(result)
        
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-20
          • 2019-07-18
          • 1970-01-01
          • 2015-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多