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:
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!
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.
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 .
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.
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.
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:
from tkinter import *import simpleaudio as safrom collections import Counter
tkinter
: To add widgets in our application.simpleaudio
: To play the sound files.Counter
: To calculate the occurrence of each character.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()
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 = name1name1 = name2name2 = name3
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")
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 stringfinal_string = name1+"LOVES"+name2#Convert string into listl1 = list(final_string)print(l1)
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 characterlist2 = l1c = Counter( list2 )list2 = list(c.values())print (list2)
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=0while n>2:num = list2[i] +list2[n-1]if num>=10:sum = 0while(num!=0):sum = sum + int(num%10)num =int(num/10)num = sumlist5 = list2[1:n-1]list5.insert(0,num)print(list5)list2 = list5n = n-1
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 stringlistToStr = "".join([str(elem) for elem in list5])#Convert the string to integervalue = int(listToStr)print(listToStr)
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 askedif value<95:if answer1=="YES" or answer1=="yes" or answer1=="Yes":value = value+5if value<90:if answer2=="YES" or answer2=="yes" or answer2=="Yes":value = value+5if value<85:if answer3=="YES" or answer3=="yes" or answer3=="Yes":value = value+5if value<80:if answer4=="YES" or answer4=="yes" or answer4=="Yes":value = value+5if value<75:if answer5=="YES" or answer5=="yes" or answer5=="Yes":value = value+5print(value)
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 filesstart = 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.
surprise = PhotoImage(file="Surprise.png")fingers = PhotoImage(file="fingers.png")#Display the love percentage in label imageresult = PhotoImage(file=str(value)+str(".png"))
1.png
2.png
3.png
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)
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 name1for i in range(n_1):l1[i] = PhotoImage(file=str(name1[i])+str("_P.png"))#Load the images for name2for j in range(n_2):l2[j] = PhotoImage(file=str(name2[j])+str("_P.png"))#Load the images for LOVESfor k in range(n_3):l3[k] = PhotoImage(file=str(l3[k])+str("_P.png"))#Show name1 as label imager1=0c1=0for i in range(n_1):B = Label(root,image=l1[i])B.grid(row=r1,column=c1)c1 = c1+1#Add blank spaceroot.grid_rowconfigure(1, minsize=10)#Show "LOVES" as image labelr2 = 2c2 = 0for k in range(n_3):B = Label(root,image=l3[k])B.grid(row=r2,column=c2)c2 = c2+1#Add blank spaceroot.grid_rowconfigure(3, minsize=10)#Show name2 as label imager4=4c4=0for j in range(n_2):B = Label(root,image=l2[j])B.grid(row=r4,column=c4)c4 = c4+1#Add blank spaceroot.grid_rowconfigure(5, minsize=10)
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)
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 functiondef close():two.play()root.destroy()
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 looproot.mainloop()
#!/usr/bin/env python# coding: utf-8# In[4]:#Import required librariesfrom tkinter import *import simpleaudio as safrom collections import Counter#Take 2 names as inputname1 = input("NAME1 : ")name2 = input("NAME2 : ")#Convert the names to upper casename1 = name1.upper()name2 = name2.upper()#Set the longer name as name1if len(name2)>len(name1):name3 = name1name1 = name2name2 = name3#Get answers to the few questionsprint("\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 stringfinal_string = name1+"LOVES"+name2#Convert string into listl1 = list(final_string)print(l1)#Count the number of occurance for each characterlist2 = l1c = Counter( list2 )list2 = list(c.values())print (list2)#Main logic to calculate the valuen = len(list2)list5 = []i=0while n>2:num = list2[i] +list2[n-1]if num>=10:sum = 0while(num!=0):sum = sum + int(num%10)num =int(num/10)num = sumlist5 = list2[1:n-1]list5.insert(0,num)print(list5)list2 = list5n = n-1#Convert the list of 2 numbers to stringlistToStr = "".join([str(elem) for elem in list5])#Convert the string to integervalue = int(listToStr)print(listToStr)#Add points based on the questions askedif value<95:if answer1=="YES" or answer1=="yes" or answer1=="Yes":value = value+5if value<90:if answer2=="YES" or answer2=="yes" or answer2=="Yes":value = value+5if value<85:if answer3=="YES" or answer3=="yes" or answer3=="Yes":value = value+5if value<80:if answer4=="YES" or answer4=="yes" or answer4=="Yes":value = value+5if value<75:if answer5=="YES" or answer5=="yes" or answer5=="Yes":value = value+5print(value)#=================================================================================================================##Configure tkinter windowroot = 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 filesstart = 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 usesurprise = PhotoImage(file="Surprise.png")fingers = PhotoImage(file="fingers.png")#Display the love percentage in label imageresult = PhotoImage(file=str(value)+str(".png"))#Play the sound filestart.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 name1for i in range(n_1):l1[i] = PhotoImage(file=str(name1[i])+str("_P.png"))#Load the images for name2for 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 imager1=0c1=0for i in range(n_1):B = Label(root,image=l1[i])B.grid(row=r1,column=c1)c1 = c1+1#Add blank spaceroot.grid_rowconfigure(1, minsize=10)#Show "LOVES" as image labelr2 = 2c2 = 0for k in range(n_3):B = Label(root,image=l3[k])B.grid(row=r2,column=c2)c2 = c2+1#Add blank spaceroot.grid_rowconfigure(3, minsize=10)#Show name2 as label imager4=4c4=0for j in range(n_2):B = Label(root,image=l2[j])B.grid(row=r4,column=c4)c4 = c4+1#Add blank spaceroot.grid_rowconfigure(5, minsize=10)#n = len(name1)#Add a buttonbtn = Button(root,image=surprise,command=lambda:Reveal())btn.grid(row=6,column=0,columnspan=n_1)#Add blank spaceroot.grid_rowconfigure(7, minsize=10)#Add a label to show the resultres = Label(root,image=fingers)res.grid(row=8,column=0,columnspan=n_1)#Function that reveals the love percentage as image labeldef Reveal():res.configure(image=result)one.play()btn.configure(command=lambda:close())two.play()#Close functiondef close():two.play()root.destroy()#Enter the main looproot.mainloop()
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
Free Resources