簡體   English   中英

tkinter 中的測驗,索引超出范圍

[英]quiz in tkinter, Index out of range

我有一個項目,目前只會問 1 個問題然后中斷,給我信息:

IndexError: list index out of range

錯誤在第 42 行,即:

label.config(text=question[q]).

這是代碼:

from tkinter import *
import tkinter as tk

q = -1
count = 0
correct = 0
incorrect = 0

question=["File compression software is an example of.. software", "Each piece of hardware e.g printer, monitor, keyboard, will need an up to date... installed", "application softwares control the computer, true or false?"]
answer = ["utility", "driver", "false"]
answer_cap = ["Utility","Driver","False"]
root = Tk()

name = tk.Label(root,text = "Computing quiz")
name.pack()

label = tk.Label(root,text = question[0])
label.pack()

entry = tk.Entry(root)
entry.pack() 

def out():
    global q,correct,incorrect,count
    while count < len(question):
          ans = entry.get()
          if answer[q] == ans or answer_cap[q] == ans :
              q+=1
              entry.delete(0, END)
              correct+=1
              print(correct)
              label.config(text=question[q])
          else:
              q+=1
              entry.delete(0, END)
              incorrect+=1
              print(incorrect)
              label.config(text=question[q])

    entry.delete(0, END)
    label.config(text = "Correct: "+str(correct) + " Incorrect:   "+str(incorrect))

    print(correct)

def stop():
    global q,correct,incorrect
    q = 0
    correct = 0
    incorrect = 0
    entry.delete(0, END)
    label.config(text = question[0])

button = tk.Button(root,text = "Submit",command = out)
button.pack()

button_two = tk.Button(root,text = "Restart",command = stop)
button_two.pack()

看看你的while循環。 您正在執行某些操作, while count < ... ,但在循環內count未更新,但q是。 因為這個q很快就會非常大,所以它會比len(question)高得多。 難怪IndexError

您必須糾正該循環,因為即使您處理了IndexErrorwhile循環也將永遠運行。

一種解決方法(我不建議這樣做,在我看來你應該只糾正整個while循環)可能是except IndexErrorbreak循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM