Building a Python Quiz Game with GUI using Tkinter
Creating interactive games is a fun way to improve your programming skills. In this blog post, we will build a simple Python quiz game with a graphical user interface (GUI) using Tkinter. This quiz game will ask multiple-choice questions and keep track of the player's score. Here's a step-by-step guide on how to create this game.
Step 1: Setting Up Your Project
First, ensure you have Python installed on your system. You can download it from the official Python website. We will use the Tkinter library, which is included with Python, so you don’t need to install it separately.
Step 2: Importing Required Libraries
Start by importing the necessary libraries. Tkinter is used for the GUI, and random is used to shuffle the questions.
import tkinter as tk
from tkinter import PhotoImage, Label, Button, Radiobutton, IntVar
import random
Step 3: Preparing the Questions and Answers
Prepare your questions and their respective answer choices. Store them in lists.
questions = [
"Total keywords in Python?",
"Which function takes a console input in Python?",
"Output of 2**3?",
"Which of the following is necessary to execute Python code?",
"Output of np.arange(1,5)?",
"The append method adds value to the list at the?",
"Keyword used to declare a function?",
"Output of 2*21?",
"Which keyword is used to create a function in Python?",
"To declare a global variable in Python we use the keyword?"
]
answer_choice = [
['33', '31', '30', '32'],
['get()', 'input()', 'gets()', 'scan()'],
['6', '8', '9', '12'],
['TURBO C', 'Py Interpreter', 'Notepad', 'IDE'],
['[1,2,3,4]', '[0,1,2,3,4]', '[1,2,3,4,5]', '[2,4,5,1,3]'],
['custom location', 'end', 'center', 'beginning'],
['define', 'dif', 'def', 'null'],
['28', '24', '42', '32'],
['function', 'void', 'fun', 'def'],
['all', 'var', 'let', 'global']
]
answers = [0, 1, 1, 1, 0, 1, 2, 2, 3, 3] # Indexes of correct answers
Step 4: Creating the Main GUI
Next, we create the main GUI window using Tkinter.
root = tk.Tk()
root.title('Python Quiz')
root.geometry("900x800")
root.config(background="#ffffff")
root.resizable(0, 0)
Step 5: Generating Random Questions
Write a function to select a random subset of questions from the list.
indexes = []
def gen():
global indexes
while len(indexes) < 5:
x = random.randint(0, 9)
if x not in indexes:
indexes.append(x)
Step 6: Displaying the Questions and Options
Create labels and radio buttons to display questions and their respective options.
def startquiz():
global lblQuestion, r1, r2, r3, r4
lblQuestion = Label(
root,
text=questions[indexes[0]],
font=('Consolas', 16),
width=500,
justify="center",
wraplength=400,
background='#ffffff',
)
lblQuestion.pack(pady=(100, 30))
global radiovar
radiovar = IntVar()
radiovar.set(-1)
r1 = Radiobutton(
root,
text=answer_choice[indexes[0]][0],
font=("Times", 12),
value=0,
variable=radiovar,
command=selected,
background='#ffffff',
)
r1.pack(pady=5)
r2 = Radiobutton(
root,
text=answer_choice[indexes[0]][1],
font=("Times", 12),
value=1,
variable=radiovar,
command=selected,
background='#ffffff',
)
r2.pack(pady=5)
r3 = Radiobutton(
root,
text=answer_choice[indexes[0]][2],
font=("Times", 12),
value=2,
variable=radiovar,
command=selected,
background='#ffffff',
)
r3.pack(pady=5)
r4 = Radiobutton(
root,
text=answer_choice[indexes[0]][3],
font=("Times", 12),
value=3,
variable=radiovar,
command=selected,
background='#ffffff',
)
r4.pack(pady=5)
Step 7: Capturing User Responses
Capture the user's selected answers and store them for scoring later.
user_answer = []
ques = 1
def selected():
global radiovar, user_answer
global lblQuestion, r1, r2, r3, r4
global ques
x = radiovar.get()
user_answer.append(x)
radiovar.set(-1)
if ques < 5:
lblQuestion.config(text=questions[indexes[ques]])
r1['text'] = answer_choice[indexes[ques]][0]
r2['text'] = answer_choice[indexes[ques]][1]
r3['text'] = answer_choice[indexes[ques]][2]
r4['text'] = answer_choice[indexes[ques]][3]
ques += 1
else:
calc()
Step 8: Calculating and Displaying the Results
Calculate the user's score based on their answers and display the results.
def showresult(score):
lblQuestion.destroy()
r1.destroy()
r2.destroy()
r3.destroy()
r4.destroy()
labelimage = Label(
root,
background="#ffffff",
border=0
)
labelimage.pack(pady=(50, 30))
labelresulttext = Label(
root,
font=('Consolas', 20),
background="#ffffff",
)
labelresulttext.pack()
if score >= 20:
img = PhotoImage(file="great.png")
labelimage.configure(image=img)
labelimage.image = img
labelresulttext.configure(text="You are Excellent!!")
elif(score >= 10 and score < 20):
img = PhotoImage(file="ok.png")
labelimage.configure(image=img)
labelimage.image = img
labelresulttext.configure(text="You can be better!!")
else:
img = PhotoImage(file="bad.png")
labelimage.configure(image=img)
labelimage.image = img
labelresulttext.configure(text="Better luck next time!!")
def calc():
global indexes, user_answer, answers
x = 0
score = 0
for i in indexes:
if user_answer[x] == answers[i]:
score += 5
x += 1
showresult(score)
Step 9: Starting the Quiz
Create a function to start the quiz and initialize the GUI components.
def startIspressed():
labelimage.destroy()
labeltext.destroy()
lblInstruction.destroy()
lblRules.destroy()
btnStart.destroy()
gen()
startquiz()
img1 = PhotoImage(file="icon.png")
labelimage = Label(
root,
image=img1,
background='#ffffff',
)
labelimage.pack(pady=(40, 0))
labeltext = Label(
root,
text='Python Quiz',
font=("Comic Sans MS", 42, "bold"),
background="#ffffff",
)
labeltext.pack(pady=(0, 50))
img2 = PhotoImage(file="start.png")
btnStart = Button(
root,
image=img2,
relief=FLAT,
border=0,
background="#ffffff",
command=startIspressed,
)
btnStart.pack()
lblInstruction = Label(
root,
text="Read The Rules And\\nClick Start Once You're Ready",
font=("Consolas", 16, "bold"),
background="#ffffff",
justify="center",
)
lblInstruction.pack(pady=(10, 40))
lblRules = Label(
root,
text="This quiz contains 10 questions\\nYou will get 20 seconds to solve a question\\nOnce you select a radio button, that will be your final choice\\nHence, think before you select",
width=100,
font=("Times", 14),
background="#000000",
foreground="#FACA2F",
)
lblRules.pack()
root.mainloop()
Conclusion
You've now created a basic Python quiz game with a GUI using Tkinter. This game will ask multiple-choice questions, keep track of the player's answers, and display their score at the end. The score grading criteria are as follows:
- Start button
- Score >= 20: You are Excellent!!
- Score >= 10 and Score < 20: You can be better!!
- Score < 10: Better luck next time!!
This project is a great way to practice Python programming and learn how to build interactive applications. Feel free to expand on this project by adding more features, such as a timer for each question or a database to store questions and answers. Happy coding!!
Top comments (0)