Python Tkinter Quiz

In this Python tutorial, I will help you learn how to create a Quiz application using Python Tkinter. A quiz app helps test user knowledge through multiple-choice questions. We’ll create an interactive GUI where users can select answers with the click of a button. The app will track correct responses and calculate the score at the end.

Let’ get in.

Python Tkinter Quiz Application Code Description

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 every time 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 a message box in Python Tkinter. Wrong answers = total questions – total correct answers, and the 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 the same, then the 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 a new question. If no questions are 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()

There are two buttons used in the program:

  • next_button: displays the result or a 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 questionnaires, 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

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.

Read Display Data in Textboxes using Python Tkinter

Complete Code

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()

You can see the output in the screenshot below.

python tkinter quiz

In this tutorial, we have learned how to create Quiz applications using Python Tkinter.

You may like the following Python Tkinter tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.