How to prevent list index out of range in python tkinter

Viewed 179
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)

The output of the code is index range out of range if the user press the check button more than 5 time and how to prevent the user from press the the check button more than or equal to five time. Is there any solution to solve this problem cause I have try a lot of ways to solve it and I failed it.

Any comment is welcomed.

4 Answers

please try to change

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)

to

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)


if question_index < 4:
   question_index += 1

Try adding this if statement for every increment. Since the list question has only 5 entries, it spits out that error if u ask for its sixth entry. (make sure u indent the increment properly to belong in the if statement.) :)

Try button enable/disable :) based on the condition

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()

You can change your skip function to this. Now what it does it I create a skip_counter variable which counts that if it is greater than 5 then it will prevent you from the error. What your ERROR actually basically means that you are trying to access your list beyond its size.

Example:

>>> 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

Code Solutions:

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]}")

Or another way is like this, just checking on your question_index variable.

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]}")
Related