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

Я создал базовый тест c, используя tkinter в python. Я хочу показать пользователю оценку, которую он получил в конце теста, но в настоящее время оценка показывает только 0. Вот код

import os
from tkinter import *
import tkinter.messagebox
import random
from PIL import ImageTk,Image
global score
score = 0
global count
count = 0
root = Tk()
root.title('Quiz')
root.config(bg = 'white')
root.geometry('770x555')

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


def ask_quit():
    if tkinter.messagebox.askokcancel("Quit", "The quiz has finished now, would you like to quit?"):
        root.destroy()

def checkResult(letter):
    global score
    if letter == currentQuestion.correct_ans:
        score += 1
    if not len(questions) == 0:
        getNewQuestion()
    else:
        result()
        ask_quit()

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

def result():
    global score
    print('result:', score)

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

Я пытаюсь распечатать счет, а затем отобразить его в окне сообщения, чтобы показать в конце теста. Если у вас есть какие-либо советы о том, как улучшить код, не стесняйтесь поделиться. Заранее спасибо!

1 Ответ

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

Вам нужно удалить строку ввода при чтении из CSV-файла:

line_sections = line.strip().split(",")

В противном случае Question.correct_ans будет иметь '\ n' в конце, и сравнение внутри checkResult() не удастся .

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