top of page

Making a better quiz ui

  • Writer: 라임 샹큼
    라임 샹큼
  • Apr 6
  • 4 min read

I reencountered classes again. I remember I had a a hard time learning how classes were different from simply defining functions. It was hard understanding the ‘self’ and had to step away from everything for a while because I was so confused. It took a lot of determination to face something that had taken me so out of it before. I realized I usually flee when things get a little bit hard. When I actually sat down and told myself I would not leave until I understood classes, I did manage to get a hang of it. I didn’t get it fully but I still got the feel of it and didn’t get completely lost when the online course started talking about importing the classes into other files. This time around it proved better and I really realized even though it's hard, you have to keep on subjecting yourself to it so you can grow familiar and eventually understand it.


#ui file

import tkinter

from tkinter import PhotoImage

from quiz_brain import QuizBrain



THEME_COLOR = "#375362"




class QuizInterface:


    def init(self,quiz_brain: QuizBrain):

        self.quiz = quiz_brain

        self.window = tkinter.Tk()

        self.window.title('Quizzler')

        self.window.config(padx = 20, pady = 20,bg=THEME_COLOR)



        self.canvas = tkinter.Canvas(height=250, width=300,bg='white',highlightthickness=0)

        self.question_text = self.canvas.create_text(150,125,text=0,font = ('arial',20,'italic'),fill='black',width=280)

        self.canvas.grid(columnspan=2,column=0,row=1,pady=50)


        self.score = tkinter.Label(text = f'Score:{self.quiz.score}',bg=THEME_COLOR)

        self.score.grid(column=1,row=0)


        check_img = PhotoImage(file='images/true.png')

        false_img =PhotoImage(file='images/false.png')


        self.check =tkinter.Button(image=check_img,highlightcolor=THEME_COLOR,command= self.click_check)

        self.check.grid(column=0,row=2)


        self.false = tkinter.Button(image=false_img, highlightcolor=THEME_COLOR, command = self.click_false)

        self.false.grid(column=1, row=2)


        self.get_next_q()


        self.window.mainloop()


    def get_next_q(self):

        if self.quiz.still_has_questions():

            self.canvas.config(bg = 'white')

            self.score.config(text =f'Score:{self.quiz.score}' )

            q_text = self.quiz.next_question()

            self.canvas.itemconfig(self.question_text,text=q_text)

        else:

            self.canvas.config(bg='white')

            self.canvas.itemconfig(self.question_text,text=f'You have reached the end of the quiz\nYour final score is {self.quiz.score}/{self.quiz.question_number}')

            self.check.config(state='disabled')

            self.false.config(state='disabled')


    def click_check(self):

        self.is_right(self.quiz.check_answer('True'))


    def click_false(self):

        self.is_right(self.quiz.check_answer('False'))


    def is_right(self,check):


        if check:

            self.canvas.config(bg = 'green')

        else:

            self.canvas.config(bg = 'red')

        self.window.after(1000, self.get_next_q)


#quiz brain file

import html


class QuizBrain:


    def init(self, q_list):

        self.question_number = 0

        self.score = 0

        self.question_list = q_list

        self.current_question = None


    def still_has_questions(self):

        return self.question_number < len(self.question_list)


    def next_question(self):

        self.current_question = self.question_list[self.question_number]

        self.question_number += 1

        q_text = html.unescape(self.current_question.text)

        return f"Q.{self.question_number}: {q_text} (True/False): "

        # user_answer = input(f"Q.{self.question_number}: {q_text} (True/False): ")

        # self.check_answer(user_answer)


    def check_answer(self, user_answer):

        correct_answer = self.current_question.answer

        if str(user_answer.lower()) == correct_answer.lower():

            self.score += 1

            return True

        else:

            return False


#question module file

class Question:


    def init(self, q_text, q_answer):

        self.text = q_text

        self.answer = q_answer


#main file

from question_model import Question

from data import question_data

from quiz_brain import QuizBrain

from ui import QuizInterface


question_bank = []

for question in question_data:

    question_text = question["question"]

    question_answer = question["correct_answer"]

    new_question = Question(question_text, question_answer)

    question_bank.append(new_question)



quiz = QuizBrain(question_bank)

interface = QuizInterface(quiz)


# while quiz.still_has_questions():

#     quiz.next_question()


print("You've completed the quiz")

print(f"Your final score was: {quiz.score}/{quiz.question_number}")


#data file

import requests



parameters = {

    'amount':10,

    'type':'boolean', #has comma at the end

}

question_data = requests.get('https://opentdb.com/api.php',params=parameters)

question_data.raise_for_status()

question_data = question_data.json()['results']




What I learned

  • quote_url = requests.get(url='https://api.kanye.rest')

  • quote_json = quote_url.json() #turns into dict, json

  • actual_quote = quote_json['quote'#find the key of the info you want

  • canvas.itemconfig(quote_text, text = actual_quote)

  • How to unescape html symbols:

    import html module

    hmtl.unescape(wanted text)

  • When creating ui classes and adding mainloop() at the end, don't want loops(while) coming after assigning class to variable

  • Specifying data type:

    can identify data type early on and will maintain that, alerting if data type is wrong


    age:int

    .

    .

    .

    age = 5.5 (reminds)

  • can expect what the funciton will return:

    def police_check(age: int) -> bool:

  • How to disable the use of buttons:

    butoon.config(state='disabled')




 
 
 

Recent Posts

See All
Stock market price alerter

Lately I’ve been getting API data from existing data and using it to get actual live data. This is done by importing requests.  This was...

 
 
 
Getting quotes and displaying them

from tkinter import * import requests def get_quote():     quote_url = requests.get(url=' https://api.kanye.rest ')     quote_json =...

 
 
 
Password Manager

import tkinter from tkinter import messagebox from tkinter import PhotoImage import random # ---------------------------- PASSWORD...

 
 
 

Comments


© 2024 by GifTED. Powered and secured by Wix

bottom of page