#python #tkinter
#python #tkinter
Вопрос:
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 wordsnn {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 wordsnn {}".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 раз, и как запретить пользователю нажимать кнопку проверки более или равное пяти раз. Есть ли какое-либо решение для решения этой проблемы, потому что я перепробовал много способов ее решения, и я потерпел неудачу.
Любые комментарии приветствуются.
Комментарии:
1. Покажите свои попытки и обратную трассировку
Ответ №1:
пожалуйста, попробуйте изменить
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)
Ответ №2:
if question_index < 4:
question_index = 1
Попробуйте добавить этот оператор if для каждого приращения. Поскольку вопрос списка содержит только 5 записей, он выдает эту ошибку, если вы запрашиваете его шестую запись. (убедитесь, что вы правильно сделали отступ для приращения, чтобы оно соответствовало оператору if.) 🙂
Ответ №3:
Попробуйте включить / отключить кнопку 🙂 в зависимости от условия
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()
Ответ №4:
Вы можете изменить свой 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 wordsnn {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 wordsnn {question[question_index]}")