In this Python tutorial, we will learn how to create a Quiz application using Python Tkinter. A quiz application is used to take input in a multiple Choice Questionnaire. Users need to select the right option for the question asked.
Overview of Python Tkinter Quiz Application
- Before we start writing code in Python Tkinter it is important to understand how things work in quiz.
- Questions is displayed with four options out of which one is the right answer.
- User clicks on the Next button after selecting the answer. Next button brings new question with new set of options.
- Once the program reaches to the last question then it displays result. The reults pops-up with the score in percentage, total right and wrong answers.
- There is a quit button hanging on the every screen incase your wants to quit the program.
Python Tkinter Quiz Application Code Description
The code is written using Object-oriented programming and the class name is Quiz.
- In the below code we have created a constructor that holds the values like the number of questions, the title of the window, questions with multiple options using the radio button, functions, etc.
- This constructor will be called everytime the program is run so we have provided all the primary function names here.
class Quiz:
def __init__(self):
self.qno=0
self.disp_title()
self.disp_ques()
self.opt_sel=IntVar()
self.opts=self.radio_buttons()
self.disp_opt()
self.buttons()
self.total_size=len(question)
self.correct=0
- def disp_res() function is created to display the result of the quiz. The final result will be displayed using message box in Python Tkinter.
- wrong answers = total questions – total correct answers and final score in percentage would be score = (correct answers / total questions) times 100
def disp_res(self):
wrong_count = self.total_size - self.correct
correct = f"Correct: {self.correct}"
wrong = f"Wrong: {wrong_count}"
score = int(self.correct / self.total_size * 100)
result = f"Score: {score}%"
mb.showinfo("Result", f"{result}\n{correct}\n{wrong}")
- check_ans() function is used here to return the correct answers.
- The function compares the user selected option with the correct option. If both are same then function returns True.
def check_ans(self, qno):
if self.opt_sel.get() == answer[qno]:
return True
- next_btn() function is used here to move to the next question. Clicking on the ‘next’ button will display new question.
- If there are no questions remaining then it will display the result.
def next_btn(self):
if self.check_ans(self.qno):
self.correct += 1
self.qno += 1
if self.qno==self.total_size:
self.disp_res()
ws.destroy()
else:
self.disp_ques()
self.disp_opt()
- buttons() function is used here to display the button on the screen or window using Python Tkinter.
- There are two buttons used in the program:
- next_button: displays the result or new question
- quit_button: Terminates the program.
def buttons(self):
next_button = Button(
ws,
text="Next",
command=self.next_btn,
width=10,
bg="#F2780C",
fg="white",
font=("ariel",16,"bold")
)
next_button.place(x=350,y=380)
quit_button = Button(
ws,
text="Quit",
command=ws.destroy,
width=5,
bg="black",
fg="white",
font=("ariel",16," bold")
)
quit_button.place(x=700,y=50)
- disp_opt() function is used here to display the options to the users for every question.
- These options are being fetched from the hard coded database that holds the questionaires, options and their answers.
def disp_opt(self):
val=0
self.opt_sel.set(0)
for option in options[self.qno]:
self.opts[val]['text']=option
val+=1
Read Convert python file to exe using pyinstaller
Source code Quiz application using Python Tkinter
Object-oriented programming is followed in this source code so that we don’t have to repeat the code. Click here to download the data file that contains questions, options, and answers for the quiz.
from tkinter import *
from tkinter import messagebox as mb
import json
class Quiz:
def __init__(self):
self.qno=0
self.disp_title()
self.disp_ques()
self.opt_sel=IntVar()
self.opts=self.radio_buttons()
self.disp_opt()
self.buttons()
self.total_size=len(question)
self.correct=0
def disp_res(self):
wrong_count = self.total_size - self.correct
correct = f"Correct: {self.correct}"
wrong = f"Wrong: {wrong_count}"
score = int(self.correct / self.total_size * 100)
result = f"Score: {score}%"
mb.showinfo("Result", f"{result}\n{correct}\n{wrong}")
def check_ans(self, qno):
if self.opt_sel.get() == answer[qno]:
return True
def next_btn(self):
if self.check_ans(self.qno):
self.correct += 1
self.qno += 1
if self.qno==self.total_size:
self.disp_res()
ws.destroy()
else:
self.disp_ques()
self.disp_opt()
def buttons(self):
next_button = Button(
ws,
text="Next",
command=self.next_btn,
width=10,
bg="#F2780C",
fg="white",
font=("ariel",16,"bold")
)
next_button.place(x=350,y=380)
quit_button = Button(
ws,
text="Quit",
command=ws.destroy,
width=5,
bg="black",
fg="white",
font=("ariel",16," bold")
)
quit_button.place(x=700,y=50)
def disp_opt(self):
val=0
self.opt_sel.set(0)
for option in options[self.qno]:
self.opts[val]['text']=option
val+=1
def disp_ques(self):
qno = Label(
ws,
text=question[self.qno],
width=60,
font=( 'ariel' ,16, 'bold' ),
anchor= 'w',
wraplength=700,
justify='center'
)
qno.place(x=70, y=100)
def disp_title(self):
title = Label(
ws,
text="PythonGuides QUIZ",
width=50,
bg="#F2A30F",
fg="white",
font=("ariel", 20, "bold")
)
title.place(x=0, y=2)
def radio_buttons(self):
q_list = []
y_pos = 150
while len(q_list) < 4:
radio_btn = Radiobutton(
ws,
text=" ",
variable=self.opt_sel,
value = len(q_list)+1,
font = ("ariel",14)
)
q_list.append(radio_btn)
radio_btn.place(x = 100, y = y_pos)
y_pos += 40
return q_list
ws = Tk()
ws.geometry("800x450")
ws.title("PythonGuides Quiz")
with open('data.json') as f:
data = json.load(f)
question = (data['question'])
options = (data['options'])
answer = (data[ 'answer'])
quiz = Quiz()
ws.mainloop()
The output of the Quiz application using Python Tkinter
- In this output, you can see that there is a Quiz application created using Python Tkinter. the application displays Title, Question, and four radio buttons to display options.
- Each time time user clicks on the Next button new question appears on the screen.
- There is a quit button hanging on the right, clicking on it will terminate the program.
You may like the following python Tkinter tutorials:
- Registration form in Python using Tkinter
- Extract text from PDF Python
- BMI Calculator Using Python Tkinter
- How to Set Background to be an Image in Python Tkinter
- Python Tkinter to Display Data in Textboxes
- What is python Django and used for
- Python Tkinter Table Tutorial
- Python Tkinter Editor
In this tutorial, we have learned how to create Quiz applications using Python Tkinter.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.