Я попытался сделать тест с использованием tkinter в python и по какой-то причине я получаю сообщение об ошибке - PullRequest
0 голосов
/ 05 февраля 2020

Я создал код для теста в python. Все работает нормально, пока мы не дойдем до конца вопросов, в этот момент нам дают ошибку. Я не понимаю, где это идет не так?

import os
from tkinter import *
import random
from PIL import ImageTk,Image
global score
score = 0
root = Tk()
root.title('Quiz')
root.config(bg = 'black')

class Question:
    def __init__(self, question, correct_ans):
        self.question = question
        self.correct_ans = correct_ans

def checkResult(letter):
    global score
    if letter == correct_ans:
        score += 1
    getNewQuestion()

def getNewQuestion():
    currentQuestion = questions.pop()
    for i, var in enumerate((titleVar, aVar, bVar, cVar, dVar)):
        var.set(currentQuestion.question[i])

def buttons():
    question = Label(root, textvariable=titleVar)
    question.pack()

    A = Button(root, textvariable = aVar, command = lambda: checkResult('A'))
    A.pack()

    B = Button(root, textvariable = bVar, command = lambda: checkResult('B'))
    B.pack()

    C = Button(root, textvariable = cVar, command = lambda: checkResult('C'))
    C.pack()

    D = Button(root, textvariable = dVar, command = lambda: checkResult('D'))
    D.pack()

file_handle = os.path.join(os.path.dirname(__file__), "easyquestion.csv") 
count = 0
score = 0

questions = []

with open('easyquestion.csv', 'r') as file_handle:
    # list_question = []
    displayQ = []
    for line in file_handle:
        line_sections = line.split(",")
        displayQ = line_sections[:-1]
        correct_ans = line_sections[-1]
        questions.append(Question(displayQ, correct_ans))

titleVar = StringVar()
aVar = StringVar()
bVar = StringVar()
cVar = StringVar()
dVar = StringVar()

currentQuestion = None
getNewQuestion()

canvas = Canvas(width = 100, height = 100, bg = 'black')
canvas.pack(expand = YES, fill = BOTH)

image = ImageTk.PhotoImage(file = "/Users/arjyo/Downloads/image.png")
canvas.create_image(10, 10, image = image, anchor = NW)

buttons()

root.mainloop()

Вам понадобится имя файла csv "easyquestion.csv", которое выглядит следующим образом

what is the smallest country in the world?,a) Monaco,b) Vatican City,c)Luxembourg,d)Maldives,B
what is the largest country in the world?,a)Russia,b)USA,c)India,d)China,A
what is the largest continent in the world?,a)Europe,b)Africa,c)Asia,d)Australia,C
When did world war 2 start?,a)1945,b)1942,c)1918,d)1939,D
What did Isaac newton discover?,a)electricity,b)gravity,c)energy,d)magnetism,B
what is the scientific name for humans?,a)hetero sapians,b)homo sapiens,c)homo exodus,d)hetero exodus,B
what is the boiling pont of water?,a)110 degree C,b)373 degree C,c)100 deegre C,d)0 degree C,C
What is 2*3*4*5*0+7-4?,a)123,b)27,c)3,d)9,C
Who owns microsoft?,a)Google,b)apple,c)Microsoft,d) ubuntu,C
what is the denary value of: 01001111,a)64,b)70,c)15,d)79,D

это ошибка, которую я получаю

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "/Users/arjyo/Documents/quiz experiments/Actual quiz trial.py", line 31, in <lambda>
    A = Button(root, textvariable = aVar, command = lambda: checkResult('A'))
  File "/Users/arjyo/Documents/quiz experiments/Actual quiz trial.py", line 20, in checkResult
    getNewQuestion()
  File "/Users/arjyo/Documents/quiz experiments/Actual quiz trial.py", line 23, in getNewQuestion
    currentQuestion = questions.pop()
IndexError: pop from empty list

любая Помощь приветствуется, и если вы видите какие-либо проблемы или способы улучшить код, сообщите мне. Заранее спасибо.

Ответы [ 2 ]

1 голос
/ 05 февраля 2020

Проблема в том, что когда он запускает checkResult для последнего вопроса, он затем вызывает getNewQuestion, который пытается выдать пустой список. Я не знаком с tkinter, но вам нужен какой-то хук, который проверяет, что вопросы не пусты, а затем что-то делает для завершения теста.

def checkResult(letter):
    global score
    if letter == correct_ans:
        score += 1
    if not len(questions) == 0:
        getNewQuestion()
    else:
        print("Quiz Complete")
        root.destroy() 
        #or call a function which deals with the quiz being over
0 голосов
/ 05 февраля 2020

попробуйте поместить этот код

questions = []

with open('easyquestion.csv', 'r') as file_handle:
    # list_question = []
    displayQ = []
    for line in file_handle:
        line_sections = line.split(",")
        displayQ = line_sections[:-1]
        correct_ans = line_sections[-1]
        questions.append(Question(displayQ, correct_ans))

после определения

def checkResult(letter):, потому что он пытается вывести пустой список в виде вопросов = []

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...