learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022
review API & OOP & make UI for Day 17-OOP & Quiz Game
Python Type Hints
def greeting(name: str) ->str:
return 'Hello '+ name
Quizzler Game
Change quiz data from list to API
import requests
parameters = {
"amount": 10,
"category": 18,
"type": "boolean"
}
response = requests.get(url="https://opentdb.com/api.php", params=parameters)
response.raise_for_status()
question_data = response.json()["results"]
Use OOP to build Tkinter
from tkinter import *
from quiz_brain import QuizBrain
THEME_COLOR = "#375362"
class QuizUI:
def __init__(self, quiz_brain: QuizBrain):
self.quiz = quiz_brain
self.screen = Tk()
self.screen.title("Quizzler-app")
self.screen.config(bg=THEME_COLOR, padx=20, pady=20)
self.score_label = Label(bg=THEME_COLOR, fg="white", font=("Arial", 15))
self.score_label.grid(row=0, column=1)
self.canvas = Canvas(height=250, width=300, bg="white")
self.question_text = self.canvas.create_text(
150,
125,
width=280,
font=("Arial", 20, "italic"),
fill=THEME_COLOR)
self.canvas.grid(row=1, column=0, columnspan=2, pady=50)
true_img = PhotoImage(file="images/true.png")
self.true_button = Button(image=true_img, highlightthickness=0, command=self.guess_true)
self.true_button.grid(row=2, column=0)
false_img = PhotoImage(file="images/false.png")
self.false_button = Button(image=false_img, highlightthickness=0, command=self.guess_false)
self.false_button.grid(row=2, column=1)
self.show_next_question()
self.screen.mainloop()
def show_next_question(self):
self.canvas.config(bg="white")
if self.quiz.still_has_questions():
quiz_text = self.quiz.next_question()
self.score_label.config(text=f"score:{self.quiz.score}")
self.canvas.itemconfigure(self.question_text, text=quiz_text)
else:
self.canvas.itemconfigure(self.question_text,
text="You've got the end of the quiz.")
self.true_button.config(state="disabled")
self.false_button.config(state="disabled")
def guess_true(self):
self.give_feedback(self.quiz.check_answer("true"))
def guess_false(self):
self.give_feedback(self.quiz.check_answer("false"))
def give_feedback(self, answer_is_right):
if answer_is_right:
self.canvas.config(bg="green")
else:
self.canvas.config(bg="red")
self.screen.after(1000, self.show_next_question)