Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Follow publication

Create a Quiz Application for Windows using Python

Introduction

Hi, everyone! Welcome to a step-by-step guide to creating/building a GUI application for Windows using Python. I want to start by telling you why I decided to write this post.

I am quite fluent in German, and my girlfriend always kept on complaining about me, not helping her with her German. So, I started teaching her German and gave her a PDF to try and memorize some vocabulary. It was “boring” for her, and she did not find it as an exciting way to learn something new. I know there are better apps there to learn German, but since she complained about me not helping her, I decided to build a Quiz app for her, thinking that she would appreciate it and get better.

The app contains basic multiple-choice questions. The users can enter their name and select whether the questions display English word, and they choose a German word for it or vice versa. They can choose the number of questions they want to answer. The last five scores are displayed, as well. The figure shows the main window of the app, along with the Q&A window.

First-look

As you can see, if somebody is not sure, they can check the meanings of all the choices displayed, select, and move to the next question or quit the game. The score is tracked and added to your display only if you finish the quiz. You can reset your scores using the Reset button at the bottom. If you want to learn, pressing the Learn button opens a PDF containing the vocabulary. (Disclaimer: The vocab is not 100% correct. Most of the articles used with the words are incorrect, because I collected the vocabulary from random sources on the internet almost 3–4 years ago.)

Pre-requisites

Knowledge: I am assuming that you know python (working with classes, libraries like pandas, Tkinter, pillow (PIL), etc.). The entire code is available at the end of this post. Explaining each line of code is beyond the scope of this post.

Software: Python with pandas and pillow installed.

So, let’s get started.

I divided the code into two different classes: one I named GenerateData and the other QuizIt. As the name suggests, I use the GenerateData to generate lists: one containing questions, the second one with their individual choices (options), and the last one having their answers. The whole GUI part is written in QuizIt. I will first explain how I generate the data and then move on to the GUI.

GenerateData: Below, you can find the code to generate different lists to be passed on to the quiz. The class takes a DataFrame (df), the number of questions (num_ques), and form (Selecting a german word for a given English word or vice a versa) as inputs. The vocabulary is extracted from an Excel file containing two columns (German and English).

import random
class GenerateData:
def __init__(self, df, num_ques, form):
self.df = df
self.num_ques = num_ques
self.form = form

The below method generates a question string in English, 4 options in German, and the correct answer and returns them. It first selects a random integer index from the data frame. Then it randomly selects 3 possibilities from the DataFrame and one right answer and then shuffles them so that the solution does not always end up being Option A, for example.

def generate_eng2ger(self):
question = []
data_len = len(self.df)+1
n = random.randint(0, data_len)
lst = []
options = []
for i in range(3):
no = random.randint(0, data_len)
lst.append(no)
lst.append(n)
lst = random.sample(lst, len(lst))

### Creating the question
question.append(f'Select a german word for "{self.df.iloc[n, 1]}":')

### Creating options/choices
for l in lst:
options.append(f'{self.df.iloc[l, 0]}')
### Allocating the answer
answer = self.df.iloc[n, 0]
return question, options, answer

Another method does the same thing but returns the question in German, and options, and answers in English.

The last method in the class considers the number of questions to be generated (specified in __init__). For example, if the user selects 25 questions, the method will return a list of 25 questions, their choices (options), and their right answers in the form of three lists, respectively.

def collection(self):
"""
Generates a collection of questions, respective multiple-choices and answers for German to English.
Returns:
questions, options, answers (in that order)
"""
questions = []
choice_list = []
answers = []
if self.form=='The correct German word':
for i in range(self.num_ques):
question, options, answer = self.generate_eng2ger()
questions.append(question)
choice_list.append(options)
answers.append(answer)
else:
for i in range(self.num_ques):
question, options, answer = self.generate_ger2eng()
questions.append(question)
choice_list.append(options)
answers.append(answer)
return questions, choice_list, answers

QuizIt: This class creates the GUI. This class has over 300 lines of code, and hence I will not be explaining it entirely. The class imports the following modules:

# Imports
import os
import pickle
import PIL
from PIL import ImageTk
import pandas as pd
from datetime import datetime
from dataprep import GenerateData
from tkinter import *
from tkinter import messagebox

As mentioned earlier, an Excel file is used to generate the data for the quiz. The below lines of code show minor pre-processing of the data.

### Preparing the dataframe
df = pd.read_excel('vocab_reduced.xlsm') # Reading the vocab from an Excel file
df.dropna(inplace=True) # Droping NaN (empty cells/values)
df.drop_duplicates(subset=['German', 'English'], keep='last', inplace=True) # Dropping words if they repeat
df.reset_index(inplace=True, drop=True)

The code is too long to paste here. It can be found here, along with the vocabulary and icons used.

Converting to .exe and creating a setup for distribution.

I use auto-py-to-exe as my goto to convert python scripts to windows executable. If you have it installed you know how to work with it. If not you can install it using:

pip install auto-py-to-exe

Once you have it, all you need to do is provide the path to the script, add an icon (if you want), name, change the output path to the directory where your additional files are (for example, in my case I had a pdf, excel and png files as additional files and so I specified it in the additional files section), and look through any other settings if it applies to you.

Converting .PY to .EXE

Note:- The .exe file generated should be placed in the same folder as your images or additional files.

.EXE Created
Creating a compressed zip folder
#1 Select INSTALLER BASED ON .ZIP FILE — — #2 Give the zip file — — Setup file is generated as you can see on the bottom left corner
The installation is just like a normal installation process and then the user can start the app using the EXE file

Now you can run this .exe on any Windows PC without installing or configuring Python. In order to make it easier to distribute or send your application to someone, you can create a setup. For that, you need to install NSIS on your PC. You can do it from here. Then create a compressed zip folder of the folder where your application(.exe) and all the data files are. Open the NSIS software by simply searching it in the windows search bar. Look at the image below. There you go. Now you can send this setup file to anyone you want and they will be able to run the application without installing Python or any libraries.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Analytics Vidhya
Analytics Vidhya

Published in Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

Vicky Parmar
Vicky Parmar

Written by Vicky Parmar

I am a Machine/Deep Learning/AI enthusiast, trying to expand and share my knowledge.

No responses yet

Write a response