Age Calculator App Using Python Tkinter


If you want to create a great-looking app using Tkinter, you have come to the right place. In this article, let’s create an age calculator app using the Tkinter library of Python.

In this age calculator app, users can type in their date of birth, and the app will calculate and display their age. Isn’t that cool? Let’s turn this idea into a cool Python app.

Open up your code editor to begin the project. First of all, we need to import three libraries into our code. 

The first one is the tkinter library. Then, we need the datetime library to work with dates. Finally, we need the PIL library, which will help us to work with images.

import datetime
import tkinter as tk
from PIL import Image,ImageTk

Now, let’s create a simple window for our app and name it “Age Calculator App”.

window=tk.Tk()
window.geometry("620x780")
window.title(" Age Calculator App ")

Then, we are going to create four labels, each for the name, year, month, and date, and put them in the grid.

name = tk.Label(text = "Name")
name.grid(column=0,row=1)
year = tk.Label(text = "Year")
year.grid(column=0,row=2)
month = tk.Label(text = "Month")
month.grid(column=0,row=3)
date = tk.Label(text = "Day")
date.grid(column=0,row=4)

We will create entry fields to get the user inputs corresponding to all the labels created. Put them on the right side of the corresponding labels using the grid method.

nameEntry = tk.Entry()
nameEntry.grid(column=1,row=1)
yearEntry = tk.Entry()
yearEntry.grid(column=1,row=2)
monthEntry = tk.Entry()
monthEntry.grid(column=1,row=3)
dateEntry = tk.Entry()
dateEntry.grid(column=1,row=4)

Then, we are going to define a function to get user inputs. We name that function as getInput(). 

Inside that function, we will create an object of the Person class (which will be defined later), and pass the name and birth date to the “__init__” method of that class.

Note that we use the predefined int() method to convert values into integer format. Then, we create a text area that will display the age of the user as output.

def getInput():
    name=nameEntry.get()
    monkey = Person(name,datetime.date(int(yearEntry.get()),int(monthEntry.get()),int(dateEntry.get())))
    
    textArea = tk.Text(master=window,height=10,width=25)
    textArea.grid(column=1,row=6)
    answer = " Heyy {monkey}!!!. You are {age} years old!!! ".format(monkey=name, age=monkey.age())
    textArea.insert(tk.END,answer)

I know my variable names are kind of weird. While naming a variable, a monkey randomly came out of my mind. However, you can try a different name, which is better than my weird ones.

Then, we are going to create a button for users to submit their input values. We link the button to the getInput function.

button=tk.Button(window,text="Calculate Age",command=getInput,bg="pink")
button.grid(column=1,row=5)

Now, let’s define the Person class. We are also going to code the __init__ method and also the age method, which will calculate the age of the user by subtracting the user’s birth date from today’s date.

class Person:
    def __init__(self,name,birthdate):
        self.name = name
        self.birthdate = birthdate
    def age(self):
        today = datetime.date.today()
        age = today.year-self.birthdate.year
        return age

Next, we are going to add an image to our app so that it will look beautiful. You need to make sure you place the image in the same folder as that of the Python file.

image=Image.open('app_image.jpeg')
image.thumbnail((300,300),Image.ANTIALIAS)
photo=ImageTk.PhotoImage(image)
label_image=tk.Label(image=photo)
label_image.grid(column=1,row=0)

Don’t forget to change the image name accordingly.

Finally, let’s run everything inside the window using the mainloop() method.

window.mainloop()

That’s it. Here is a quick look at the entire code that we have written to create the app.

That’s it. Here is a quick look at the entire code.

When we run the code, the user interface of the app will look like this. 

Age Calculator using tkinter

You can add your favorite images to make the app look excellent. If you have any trouble adding images to your app, don’t worry. Let’s learn how to add images to Tkinter apps.

Adding Images to Your Python Tkinter App

We can add beautiful images to our Tkinter app to make its user interface looks attractive. To implement this, we need a library called ‘PIL’.  
If you don’t have this marvelous library already, go to your command prompt or PowerShell, and type in the following command and press the Enter key:  

easy_install Pillow

This library will help you make your apps look stunning.

After installing PIL, you can create your python desktop apps more efficiently. An example code is given below to help you use PIL.

from PIL import Image,ImageTk  #import the PIL library to our code
image = Image.open('Path' )     #specify the path of the image
image.thumbnail((100,100),Image.ANTIALIAS)    #100,100 is the resolution
#ANTIALIAS helps to deal some problems while using images
photo= ImageTk.PhotoImage(image)   #converts the image to a tkinter image
label_image= tk.Label(image=photo)  #stores the image in a label
label_image.grid(column=1,row=0)    #Puts it in a grid

You can boost the beauty of your Tkinter apps with these few lines of code. 

Conclusion

We have created a great-looking app using Python, and I hope you did an excellent job. Congratulations on finishing your age calculator app!

If you have any doubts or queries, put them down in the comments section. I will be happy to help you.

Now, it’s time to level up your programming skills. Try to create more apps and build as many projects as you can.

Make use of the sea of online resources available to learn to code and do projects. If you’re the kind of person who loves to learn with the help of a book, then I can suggest some good books for you. Go check out my resources page to take a look at my recommended technical books. I hope it will help you.

If you enjoyed this tutorial, I would appreciate it if you would be willing to share it. It will encourage me to create more useful tutorials like this.

Happy coding!

Ashwin Joy

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

16 thoughts on “Age Calculator App Using Python Tkinter

    1. Check out the full code here: https://github.com/AshwinJoy/My-Python-Apps/tree/master/Age_Calculator_App. I hope you can debug the issue by looking at this repository.

  1. I have done coding for an Online age calculator in Slim. Slim is a PHP micro-framework but I am thinking to move into Python. It will good for me.

  2. Hey
    There is a problem like this:

    File “E:\Pyprojects\Age_Calculator.py”, line 50, in
    img=Image.open(r”E:\Pyprojects\appimg1.jpg”)
    AttributeError: type object ‘Image’ has no attribute ‘open’

    Now, what should I do?

      1. This is my code:

        import tkinter as tk
        from PIL import Image,ImageTk
        import PIL
        root=tk.Tk()
        root.geometry(“620×780”)
        root.title(“Age Calci”)

        img=PIL.Image.open(r”E:\Pyprojects\appimg1.jpg”)
        img.thumbnail((300,300),Image.ANTIALIAS)
        photo=ImageTk.PhotoImage(img)
        label_img=tk.Label(img=photo)

        label_img.grid(column=1,row=0)

        root.mainloop()

        And I saw this error:

        Traceback (most recent call last):
        File “E:/Pyprojects/tryimg.py”, line 10, in
        label_img=tk.Label(img=photo)
        File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py”, line 3143, in __init__
        Widget.__init__(self, master, ‘label’, cnf, kw)
        File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py”, line 2567, in __init__
        self.tk.call(
        _tkinter.TclError: unknown option “-img”

        1. Check out this GitHub repo for help: https://github.com/AshwinJoy/My-Python-Apps/tree/master/Age_Calculator_App

    1. hi Ashwin
      I have done your age calculator and checked it against your code and cant see an error. Please could you help as I am learning so much from your content and it infuriates me when i cant see an error

      PS C:\Users\steco\OneDrive\Desktop\agecalc> python -u “c:\Users\steco\OneDrive\Desktop\agecalc\main.py”
      Traceback (most recent call last):
      File “c:\Users\steco\OneDrive\Desktop\agecalc\main.py”, line 7, in
      window.geometry(“720 x 780”)
      File “C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py”, line 2100, in wm_geometry
      return self.tk.call(‘wm’, ‘geometry’, self._w, newGeometry)
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      _tkinter.TclError: bad geometry specifier “720 x 780”
      PS C:\Users\steco\OneDrive\Desktop\agecalc>

  3. Hello sir,

    I am confused about this statement{“”””monkey = Person(name,datetime.date(int(yearEntry.get()),int(monthEntry.get()),int(dateEntry.get())))””””}
    can you help me to get me out to this confusion.

    1. Hi Abhishek,

      Here, we are creating an object of the Person class (which is defined later). We pass the name and birth date to the “__init__” method of that class when we create the object. We use the datetime module of Python here and its date method which has the year, month, and date as the arguments.

  4. My birthday is on December 28 and it is today January 1. Your calculation assumes that a birthday is earlier in the same year as today, so it is too old by 1.

    I changed it to age = int(((today-self.birthdate).days)/365.2425)

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts