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