Movatterモバイル変換


[0]ホーム

URL:


How to Detect Gender by Name using Tkinter in Python

Learn how to extract gender from first name using genderize.io API and build a GUI around it with Tkinter in Python.
  · 9 min read · Updated aug 2022 ·Application Programming Interfaces ·GUI Programming

Confused by complex code? Let ourAI-powered Code Explainer demystify it for you. Try it out!

Gender prediction is becoming a more popular topic within technology and throughout the world. A gender predictor application would come in handy if a blog website hosted a poll, survey, or product review. If the owners were to find out the gender that has the most votes, they would instead use a gender predictor application to find the gender of the voters and find the number of genders that have voted most rather than trying to figure out the gender of the names manually themselves.

In this article, we will build a gender predictor application withTkinter, the Python GUI toolkit, and an API fromgenderize.io. We will use the Genderize API to determine the gender of the user's first name, this API is completely free, and it needs no API Key to be able to make API requests.  

At the end of this article, we are going to build an application that looks like this:

We will make this application from the ground up.

Table of contents:

Setting up the Project

The first task is to set up the project. Let's install therequests library:

$ pip install requests

Then create a folder and name itgenderpredictor andcd into the folder:

$ mkdir genderpredictor$ cd genderpredictor

Inside thegenderpredictor folder, create a file and name itgenderize_app.py, this is not a convention. Feel free to name it whatever you want:

Designing the Graphical User Interface (GUI)

We will, first of all, create the main window that will contain all the other widgets (frames, labels, entry, button), open the file, and paste the following code:

# importing everything from tkinterfrom tkinter import *# tkinter message box to display errorsfrom tkinter.messagebox import showerror# colors for the applicationgold = '#dca714'brown = '#31251d'# creating the main windowwindow = Tk()# defining the demensions of the window, width(325), height(300), 500+200 center the windowwindow.geometry('325x300+500+200')# this is the title of the applicationwindow.title('Gender Predictor')# this makes the window unresizablewindow.resizable(height=FALSE, width=FALSE)window.mainloop()

Let us break this code a bit, we are creating the main window usingTk() function, and we are giving this window dimensions and a title using thegeometry() andtitle() functions. Theresizable() with attributes set toFALSE will make the main window non-resizable, and finally, we want to run the window as a loop until the user closes.

Run the program, and the output will be as below:

Now inside the created window, let us create two frames, the top frame and the bottom frame, below this line of code:

window.resizable(height=FALSE, width=FALSE)

Paste this code:

"""The two frames"""# this is the top frame inside the main windowtop_frame = Frame(window, bg=brown, width=325, height=80)top_frame.grid(row=0, column=0)# this is the bottom frame inside the main windowbottom_frame = Frame(window, width=300, height=250)bottom_frame.grid(row=1, column=0)

Here we are creating two frames, the top frame and the bottom frame, and all these frames are placed inside the main window. We are setting dimensions to both these frames usingwidth andheight attributes. The top frame takesbg as an additional attribute, this will set the top frame's background color tobrown.

Running the program, the output will be:

Inside the top frame, let's create the two labels; just below the frames, paste this code:

# the label for the big title inside the top_framefirst_label = Label(top_frame, text='GENDER PREDICTOR', bg=brown, fg=gold, pady=10, padx=20, justify=CENTER, font=('Poppins 20 bold'))first_label.grid(row=0, column=0)# the label for the small text inside the top_framesecond_label = Label(top_frame, text='Give me any name and i will predict its gender', bg=brown, fg=gold, font=('Poppins 10'))second_label.grid(row=1, column=0)

The above code snippet will create two labels that will be placed inside the top frame.

Now run the program, and you'll get something like this:

This time, we will create the remaining widgets in the bottom frame; just right after the two labels, paste this code:

"""below are widgets inside the top_frame"""# the name labellabel = Label(bottom_frame, text='NAME:', font=('Poppins 10 bold'), justify=LEFT)label.place(x=4, y=10)# the entry for entering the user's namename_entry = Entry(bottom_frame, width=25, font=('Poppins 15 bold'))name_entry.place(x=5, y=35)# the empty name label, it will be used to display the namename_label = Label(bottom_frame, text='', font=('Poppins 10 bold'))name_label.place(x=5, y=70)# the empty gender label, it will be used to display the gendergender_label = Label(bottom_frame, text='', font=('Poppins 10 bold'))gender_label.place(x=5, y=90)# the empty probability label, it will be used to display the gender probalilityprobability_label = Label(bottom_frame, text='', font=('Poppins 10 bold'))probability_label.place(x=5, y=110)# the predict buttonpredict_button = Button(bottom_frame, text="PREDICT", bg=gold, fg=brown, font=('Poppins 10 bold'))predict_button.place(x=5, y=140)

The above code snippet creates the remaining widgets, the four labels, the entry, and the button inside the bottom frame.

Let us run the program, and this is the output:

Congratulations on successfully designing the application's user interface!

Implementing the Gender Predictor Functionality

Now that the user interface is complete, let us focus on implementing the predict gender functionality. We will create a function that will handle all this for us, just below the:

# importing everything from tkinterfrom tkinter import *# tkinter message box to display errorsfrom tkinter.messagebox import showerror

Paste these lines of code:

# the requests will be used for making requests to the APIimport requests

The URL that we will be using will take this format:

https://api.genderize.io?name={YOUR_NAME}

Thegenderize.io website provides a playground where you can test the API. You can access ithere.

Let us now create the function for predicting the gender, let us name itpredict_gender(), and make it look like this:

def predict_gender():    # executes when code has no errors    try:        # getting the input from entry        entered_name = name_entry.get()        # making a request to the API, the user's entered name is injected in the url        response = requests.get(f'https://api.genderize.io/?name={entered_name}').json()        # getting name from the response        name = response['name']        # getting gender from the response          gender = response['gender']        # getting probability from the response         probability = 100 * response['probability']        # adding name to the label that was empty, the name is being uppercased        name_label.config(text='The name is ' + name.upper())        # adding gender to the label that was empty, the gender is being uppercased          gender_label.config(text='The gender is ' + gender.upper())        # adding probability to the label that was empty        probability_label.config(text='Am ' + str(probability) + '%' + ' accurate')    # executes when errors are caught    # KeyError, ConnectionTimeoutError       except:        showerror(title='error', message='An error occurred!! Make sure you have internet connection or you have entered the correct data')

The above function gets name data from the entry using theget() function, and this name is passed to the API URL. The request is then sent to the API to get a response. After getting the response, the response is converted to JSON using thejson() function, and from this JSON data, the name, the gender, and the probability are retrieved using keys, and they are plugged into their respective labels.

We're also wrapping the whole code in atry/except block and show a window error whenever an error occurs.

After creating the function, let us connect it with thePredict button; we want the function to be triggered when the user clicks it. TheButton() widget in Tkinter takes an argument calledcommand, so replace thepredict_button variable with this:

predict_button = Button(bottom_frame, text="PREDICT", bg=gold, fg=brown, font=('Poppins 10 bold'), command=predict_gender)

Now let us test the application, run it and enter the name jane and click the button:

The application is working as we expected!

Now let us run the application again, but this time we will leave the entry empty and click on thePredict button:

Conclusion

That's it! We hope you enjoyed this article on how to build a gender predictor application with Tkinter and the Genderize API. We hope that you will incorporate the knowledge you have gained into your future applications.

You can getthe complete code here.

Happy coding ♥

Save time and energy with ourPython Code Generator. Why start from scratch when you can generate? Give it a try!

View Full Code Explain The Code for Me
Sharing is caring!



Read Also


How to Build a GUI Currency Converter using Tkinter in Python
How to Make a Markdown Editor using Tkinter in Python
How to Make a Typing Speed Tester with Tkinter in Python

Comment panel

    Got a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!





    Ethical Hacking with Python EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Ethical Hacking with Python EBook - Topic - Bottom

    CodingFleet - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Ethical hacking with Python from Scratch Chapter.

    See how the book can help you build awesome hacking tools with Python!



    [8]ページ先頭

    ©2009-2026 Movatter.jp