Python Tkinter Tutorial: create a love percentage calculator game

Sep 16, 2020 - 9 min read
Pratik Shukla
editor-page-cover


This article is part of a Python Tkinter series written by Pratik Shukla. Check out his Medium account to read his other articles. And stay tuned for more Tkinker articles from Pratik!

This series aims to further your knowledge of Tkinter, Python’s standard interface to the Tk GUI toolkit by building interactive games you can add to your resume. To get up to speed on Tkinter, go read our first article in this series Python Tkinter Tutorial: build a number guessing game. Once you get down the basics, come back here to build a fun love calculator from scratch!

Today, we will cover:


Love calculator game walkthrough

Today, we’ll develop a game that will calculate the love percentage between two input names. In this game, you just have to enter two names and answer some basic yes-or-no questions. In the end, you’ll generate the love percentage between these two people.

Let’s develop the same game using Python 3 and Tkinter!


Rules and how to play

  1. Run the program.
  2. Enter all the required information.
  3. Click on the surprise button in Tkinter window.
  4. See the result.
  5. Close and play again.
svg viewer
Game Flowchart

Walkthrough of the program

When the user runs the program, they will be asked to enter two names to calculate a love percentage for. After the user enters the names, they will be asked five different yes-or-no to answer. Our program will use these answers to calculate the value of love percentage later in our program.

Now our program will calculate the love percentage based on the letters in the two names entered. Then, it will use the answer values to increase the love percentage. Now, after all the inputs are answered, our program will open the Tkinter window, which will display both the names separated by “LOVES”.

For example: If the user entered “Chandler” and “Monica” as two names, our program will display “Chandler Loves Monica”.

There will be a button under the second name. When the user presses the button, it will reveal the love percentage as an image. The user can then close the program and play again.


Calculation process

Let’s look at an example to understand how the program counts the love percentage by letters in the names:

The program will count the occurrence of all the characters according to their order. The more letters are shared in the name, the higher the rating.

For example: Take the names Chandler and Monica. Here, the first character is “C”. So our program will search through the list to find an other occurrence of “C”. If there is another “C”, it’ll increase the counter for “C” by 1. Our program will proceed until it reaches the end of the list.

So, how will it calculate the percentage? We will use the output from the previous calculations. Our program is going to take the first and last number and add it. If the addition is ≥10, then it will add them internally.

For example: A score of 14 letters will be 1+4=51+4= 5.

Once it adds the first and last numbers, it will store the addition in the first place and it will delete the last element and this will go on until there are only two numbers left.

svg viewer
Example of Number Breakdown

After we have the a value for love percentage, we will use the answer values to increase the percentage. If the current value is low, then we will increase it by 5 points. Keep in mind that you can modify your program as you wish by specifying various conditions.


Final result

1. Take the required input from the user

1 of 5


Game implementation in Python (16 steps)

Now that we have a sense of what the love calculator will entail, let’s walk step-by-step through the process in Python. If you don’t yet know how to set up Tkinter, check out our first article in this series for a brief tutorial.

Implementing this game requires two parts:

  • Taking input from user
  • Displaying the output on Tkinter window

1. Import the required libraries

from tkinter import *
import simpleaudio as sa
from collections import Counter
  • tkinter: To add widgets in our application.
  • simpleaudio: To play the sound files.
  • Counter: To calculate the occurrence of each character.

2. Take input names

Here, we take two name inputs from user. The user must enter the name values After, we convert the inputs into upper case so that it aligns with our file names.

name1 = input("NAME1 : ")
name2 = input("NAME2 : ")

name1 = name1.upper()
name2 = name2.upper()

3. Set the longer name as name1

Here, we set the longer name as name1 and the shorter name as name2 so that it doesn’t distort our Tkinter module. If the lengths of both names are equal, then we do not make this change.

if len(name2)>len(name1):
    name3 = name1
    name1 = name2
    name2 = name3

4. Get answers for the questions

Here, we take inputs from user for our questions. We’re going to use the result of these questions to calculate the love percentage later in our program. The user must enter yes or no.

print("\n")
print("Reply the following questions in YES OR NO : \n")
answer1 = input("Does your partner makes you a better person? : \n")
answer2 = input("\nDoes it gives you butterflies in your stomach when you see him/her ? : \n")
answer3 = input("\nIs your partner your best friend? : \n")
answer4 = input("\nAre you willing to sacrifice your own need for him/her? : \n")
answer5 = input("\nDo you accept your partner for who he/she is? : \n")

5. Final string

Here, we calculate the final string by adding LOVES in between the two names.

For example: If our two name inputs are “Chandler” and “Monica”, then our final string will be “Chandler Loves Monica”. Then, we convert the string into list.

#Get the final string 
final_string = name1+"LOVES"+name2

#Convert string into list 
l1 = list(final_string)
print(l1)

6. Calculate the occurrence of each character

Here, we calculate the occurrence of each character in our list. As the result of this, list2 stores the number of occurrences for each characters.

#Count the number of occurance for each character 
list2 = l1

c = Counter( list2 )
list2 = list(c.values())
print (list2)

7. Write the main logic

We now calculate the value of the love percentage based on the two input names. We create an empty list called list 5. Our program is going to take the first and last numbers from the list and add them.

If the number is ≥10, it will add the digits internally to make a single digit number. Then we remove the last digit from our list. Now we insert the value of addition operation we performed at the 0th index.

List 5 will store the updated values of list 2 after removing the last number and inserting the addition value at 0th index. Then we update list 2 with list 5, so that this operation can continue on the new list.

This operation will continue until there are only 2 numbers remaining. List 5 should have only two numbers in it that. we use to calculate the percentage alongside the yes-or-no questions.

n = len(list2)
list5 = []
i=0
while n>2:
    num = list2[i] +list2[n-1]

    if num>=10:
        sum = 0
        while(num!=0):
            sum = sum + int(num%10)
            num =int(num/10)
        num = sum

    list5 = list2[1:n-1]
    list5.insert(0,num)
    print(list5)
    list2 = list5
    n = n-1

8. Convert list to int value

We now convert the list of two numbers to string. Then, we convert it to an integer so that we can further modify it based on the answer of the questions given by user.

#Convert the list of 2 numbers to string 
listToStr = "".join([str(elem) for elem in list5])   

#Convert the string to integer 
value = int(listToStr)
print(listToStr)       

9. Modifying value based on the answers for the questions

We increase the love score based on the answers to the questions. We only increase the value if it’s less than 95. If the answer to the first question is “YES”, increase the value by 5.

If the value is less than 90, we increasing the value by 5 more. This process continues for 5 if-statements. The purpose of this code is to emphasize the structure of nested if-statements.

Keep in mind that there are many ways to increase the value for love percentage. You can use you creative imagination here!

#Add points based on the questions asked 
if value<95:
    if answer1=="YES" or answer1=="yes" or answer1=="Yes":
        value = value+5
    if value<90:
        if answer2=="YES" or answer2=="yes" or answer2=="Yes":
            value = value+5
        if value<85:
            if answer3=="YES" or answer3=="yes" or answer3=="Yes":
                value = value+5
            if value<80:
                if answer4=="YES" or answer4=="yes" or answer4=="Yes":
                    value = value+5
                if value<75:
                    if answer5=="YES" or answer5=="yes" or answer5=="Yes":
                        value = value+5

print(value)

10. Main window of Tkinter and sound files

root = Tk()
root.geometry("+100+0")
root.configure(bg="#000000")
root.iconphoto(True,PhotoImage(file="Surprise.png"))
root.title("Love Percentage Game")
root.resizable(width=False,height=False)

#Load sound files 
start = sa.WaveObject.from_wave_file("Start.wav")
one = sa.WaveObject.from_wave_file("Win.wav")
two = sa.WaveObject.from_wave_file("6.wav")
  • root = Tk( ): This is used to initialize our tkinter module.
  • root.title( ): We use it to set the title for our application.
  • root.geometry( ): We use this to specify at which location our application window will open.
  • root.configure( ): We use this to specify the background color for our application.
  • root.resizable( ): Here we are using it to prevent the users from resizing our main window.
  • root.iconphoto( ): We use it to set the icon in the title bar for our application window. We set the first parameter to True, so that all windows have the same icon.

Then we add the found files that will play at various events. One thing to notice is that the program only accepts .wav files. We need to load the sound file as an object. Then we can play it using .play( ) method.


11. Load images

surprise = PhotoImage(file="Surprise.png")
fingers = PhotoImage(file="fingers.png")

#Display the love percentage in label image 
result = PhotoImage(file=str(value)+str(".png"))
  • We’re going to use surprise image as button.
  • We’re going to use fingers image as label.
  • After we’ve calculated the love percentage, we show it as an image. Here notice that our digit images are stored like:
    • 1.png
    • 2.png
    • 3.png

12. Find the length and make a list

We display each letter as a label, so we need to make the list. We use a loop to display the images for each letter, so we need to find the length of each name. Notice that here we convert the “LOVES” string to a list and find its length.

n_1 = len(name1)
n_2 = len(name2)

l1 = list(name1)
l2 = list(name2)

l3 = list("LOVES")
n_3 = len(l3)

13. Loading and showing the images

Here, we load the images for each of the letters for name1, name2 and loves. Then we display the label images for name1 and then add a blank space in the next row. Notice that our loop will run for each character. As it runs, it will increase the column value by 1 so that all the letters are placed side-by-side. We do the same for name2 and loves.

#Load the images for name1 
for i in range(n_1):
    l1[i] = PhotoImage(file=str(name1[i])+str("_P.png"))
    
#Load the images for name2 
for j in range(n_2):
    l2[j] = PhotoImage(file=str(name2[j])+str("_P.png"))
    
#Load the images for LOVES 
for k in range(n_3):
    l3[k] = PhotoImage(file=str(l3[k])+str("_P.png"))

#Show name1 as label image 
r1=0
c1=0
for i in range(n_1):
    B = Label(root,image=l1[i])
    B.grid(row=r1,column=c1)
    c1 = c1+1

#Add blank space 
root.grid_rowconfigure(1, minsize=10)

#Show "LOVES" as image label 
r2 = 2
c2 = 0
for k in range(n_3):
    B = Label(root,image=l3[k])
    B.grid(row=r2,column=c2)
    c2 = c2+1

#Add blank space 
root.grid_rowconfigure(3, minsize=10)

#Show name2 as label image 
r4=4
c4=0
for j in range(n_2):
    B = Label(root,image=l2[j])
    B.grid(row=r4,column=c4)
    c4 = c4+1

#Add blank space 
root.grid_rowconfigure(5, minsize=10)    

14. Adding button

Here, we add a button that will trigger the Reveal( ) function. Then we set the button in the center of the window by using columnspan. We then add a blank space and a label that will show the result when the user presses the button.

#Add a button :
btn = Button(root,image=surprise,command=lambda:Reveal())
btn.grid(row=6,column=0,columnspan=n_1)

#Add blank space :
root.grid_rowconfigure(7, minsize=10)

#Add a label to show the result :
res = Label(root,image=fingers)
res.grid(row=8,column=0,columnspan=n_1)

15. Reveal( ) and close( ) function

When the user presses the button, this function will be triggered. Here, we show the image label that will display the love percentage. If the user presses the button again, it uses the close( ) function to close our application. The close( ) function will play a sound file before closing the window.

#Function that reveals the love percentage as image label :
def Reveal():
    res.configure(image=result)
    one.play()
    btn.configure(command=lambda:close())
    two.play()
    
#Close function 
def close():
    two.play()
    root.destroy()  

16. Enter the main loop

We have to enter the main loop to run the program. Our program will remain in the main loop until we press the close button.

#Enter the main loop 
root.mainloop()

Putting it all together

Take a look at the complete code for this Python Tkinter game.

Want to download the code and images? You can download all the necessary images and code here.

#!/usr/bin/env python
# coding: utf-8

# In[4]:


#Import required libraries 
from tkinter import *
import simpleaudio as sa
from collections import Counter


#Take 2 names as input 
name1 = input("NAME1 : ")
name2 = input("NAME2 : ")

#Convert the names to upper case 
name1 = name1.upper()
name2 = name2.upper()
    
#Set the longer name as name1 
if len(name2)>len(name1):
    name3 = name1
    name1 = name2
    name2 = name3

#Get answers to the few questions 
print("\n")
print("Reply the following questions in YES OR NO : \n")
answer1 = input("Does your partner makes you a better person? : \n")
answer2 = input("\nDoes it gives you butterflies in your stomach when you see him/her ? : \n")
answer3 = input("\nIs your partner your best friend? : \n")
answer4 = input("\nAre you willing to sacrifice your own need for him/her? : \n")
answer5 = input("\nDo you accept your partner for who he/she is? : \n")


#Get the final string 
final_string = name1+"LOVES"+name2

#Convert string into list 
l1 = list(final_string)
print(l1)

#Count the number of occurance for each character 
list2 = l1

c = Counter( list2 )
list2 = list(c.values())
print (list2)

#Main logic to calculate the value 
n = len(list2)
list5 = []
i=0
while n>2:
    num = list2[i] +list2[n-1]

    if num>=10:
        sum = 0
        while(num!=0):
            sum = sum + int(num%10)
            num =int(num/10)
        num = sum

    list5 = list2[1:n-1]
    list5.insert(0,num)
    print(list5)
    list2 = list5
    n = n-1


#Convert the list of 2 numbers to string 
listToStr = "".join([str(elem) for elem in list5])   

#Convert the string to integer 
value = int(listToStr)
print(listToStr)       


#Add points based on the questions asked 
if value<95:
    if answer1=="YES" or answer1=="yes" or answer1=="Yes":
        value = value+5
    if value<90:
        if answer2=="YES" or answer2=="yes" or answer2=="Yes":
            value = value+5
        if value<85:
            if answer3=="YES" or answer3=="yes" or answer3=="Yes":
                value = value+5
            if value<80:
                if answer4=="YES" or answer4=="yes" or answer4=="Yes":
                    value = value+5
                if value<75:
                    if answer5=="YES" or answer5=="yes" or answer5=="Yes":
                        value = value+5

print(value)
    

#=================================================================================================================#
    
#Configure tkinter window 
root = Tk()
root.geometry("+100+0")
root.configure(bg="#000000")
root.iconphoto(True,PhotoImage(file="Surprise.png"))
root.title("Love Percentage Game")
root.resizable(width=False,height=False)

#Load sound files 
start = sa.WaveObject.from_wave_file("Start.wav")
one = sa.WaveObject.from_wave_file("Win.wav")
two = sa.WaveObject.from_wave_file("6.wav")

#Load images we're going to use 
surprise = PhotoImage(file="Surprise.png")
fingers = PhotoImage(file="fingers.png")

#Display the love percentage in label image 
result = PhotoImage(file=str(value)+str(".png"))

#Play the sound file 
start.play()

n_1 = len(name1)
n_2 = len(name2)

l1 = list(name1)
l2 = list(name2)

l3 = list("LOVES")
n_3 = len(l3)

#Load the images for name1 
for i in range(n_1):
    l1[i] = PhotoImage(file=str(name1[i])+str("_P.png"))
    
#Load the images for name2 
for j in range(n_2):
    l2[j] = PhotoImage(file=str(name2[j])+str("_P.png"))
    
#Load the images for LOVES :
for k in range(n_3):
    l3[k] = PhotoImage(file=str(l3[k])+str("_P.png"))
    
    
#Show name1 as label image 
r1=0
c1=0
for i in range(n_1):
    B = Label(root,image=l1[i])
    B.grid(row=r1,column=c1)
    c1 = c1+1

#Add blank space 
root.grid_rowconfigure(1, minsize=10)

#Show "LOVES" as image label 
r2 = 2
c2 = 0
for k in range(n_3):
    B = Label(root,image=l3[k])
    B.grid(row=r2,column=c2)
    c2 = c2+1

#Add blank space 
root.grid_rowconfigure(3, minsize=10)

#Show name2 as label image 
r4=4
c4=0
for j in range(n_2):
    B = Label(root,image=l2[j])
    B.grid(row=r4,column=c4)
    c4 = c4+1

#Add blank space 
root.grid_rowconfigure(5, minsize=10)    

#n = len(name1)

#Add a button 
btn = Button(root,image=surprise,command=lambda:Reveal())
btn.grid(row=6,column=0,columnspan=n_1)

#Add blank space 
root.grid_rowconfigure(7, minsize=10)

#Add a label to show the result 
res = Label(root,image=fingers)
res.grid(row=8,column=0,columnspan=n_1)



#Function that reveals the love percentage as image label 
def Reveal():
    res.configure(image=result)
    one.play()
    btn.configure(command=lambda:close())
    two.play()

#Close function 
def close():
    two.play()
    root.destroy()
    
#Enter the main loop 
root.mainloop()

Wrapping up and resources

Congrats! You’ve reached the end and built a successful Python Tkinter game. Great work applying your Python knowledge. I hope you enjoyed this article and learned something new from it.

Python is such an intuitive programming language that the easiest way to master it is through hands-on practice like this. Keep up the work and keep building!

In this series on Tkinter, we’ll be developing a total of Five games using Tkinter. So, hang tight! If you have any doubts, questions, or thoughts regarding this article, feel free to contact me at shuklapratik22@gmail.com


Continue learning


WRITTEN BYPratik Shukla

Join a community of 270,000 monthly readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.