Age calculator using Tkinter in Python

In this tutorial, we will learn how to make an age calculator from date of birth GUI application in Python using Tkinter.

Before we start it is important to know about tkinter in brief.

Python language provides various options for developing GUI (Graphic user interface). Python combined with tkinter provides the fastest and easiest way of creating GUI applications.
To create a GUI application using tkinter you need to perform the following steps:

  • Import the tkinter module.
  • Create a GUI application window.
  • Add the widgets to the main window.
  • Apply event triggers on the widgets.

For further information on tkinter library refer to the following link:https://docs.python.org/3/library/tk.html

Now let’s start designing the Age Calculator to calculate the age in years months and days using a given date and birth date both entered by the user.

from tkinter import *
from tkinter import messagebox

def clear():
    """Clear all the text fields."""
    day_field.delete(0, END)
    month_field.delete(0, END)
    year_field.delete(0, END)
    todays_day_field.delete(0, END)
    todays_month_field.delete(0, END)
    todays_year_field.delete(0, END)
    resultant_day_field.delete(0, END)
    resultant_month_field.delete(0, END)
    resultant_year_field.delete(0, END)

def checkError():
    """Check for input errors in the fields."""
    if (day_field.get() == "" or month_field.get() == "" or
            year_field.get() == "" or todays_day_field.get() == "" or
            todays_month_field.get() == "" or todays_year_field.get() == ""):
        messagebox.showerror("Input Error", "Please fill all the fields.")
        clear()
        return -1

def calculateAge():
    """Calculate the age based on input."""
    if checkError() == -1:
        return
    
    birth_day = int(day_field.get())
    birth_month = int(month_field.get())
    birth_year = int(year_field.get())

    given_day = int(todays_day_field.get())
    given_month = int(todays_month_field.get())
    given_year = int(todays_year_field.get())

    month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    # Checking for leap year
    if (birth_year % 4 == 0 and birth_year % 100 != 0) or (birth_year % 400 == 0):
        month[1] = 29

    if birth_day > given_day:
        given_month -= 1
        given_day += month[birth_month-1]

    if birth_month > given_month:
        given_year -= 1
        given_month += 12

    calculated_day = given_day - birth_day
    calculated_month = given_month - birth_month
    calculated_year = given_year - birth_year

    resultant_day_field.insert(10, str(calculated_day))
    resultant_month_field.insert(10, str(calculated_month))
    resultant_year_field.insert(10, str(calculated_year))

if __name__ == "__main__":
    window = Tk()
    window.title("Age Calculator")
    window.geometry("600x300")

    # Define labels and place them
    Label(window, text="Date Of Birth", fg='Red', font=('Comic Sans MS', 15)).grid(row=0, column=1)
    Label(window, text="Day", fg='Blue').grid(row=1, column=0)
    Label(window, text="Month", fg='Blue').grid(row=2, column=0)
    Label(window, text="Year", fg='Blue').grid(row=3, column=0)
    Label(window, text="Today's Date", fg='Red', font=('Comic Sans MS', 15)).grid(row=0, column=4)
    Label(window, text="Today's Day", fg='Blue').grid(row=1, column=3)
    Label(window, text="Today's Month", fg='Blue').grid(row=2, column=3)
    Label(window, text="Today's Year", fg='Blue').grid(row=3, column=3)
    Label(window, text="Years", fg='Blue').grid(row=5, column=2)
    Label(window, text="Months", fg='Blue').grid(row=7, column=2)
    Label(window, text="Days", fg='Blue').grid(row=9, column=2)

    # Define entry fields and place them
    day_field = Entry(window)
    month_field = Entry(window)
    year_field = Entry(window)
    todays_day_field = Entry(window)
    todays_month_field = Entry(window)
    todays_year_field = Entry(window)
    resultant_year_field = Entry(window)
    resultant_month_field = Entry(window)
    resultant_day_field = Entry(window)
    
    day_field.grid(row=1, column=1)
    month_field.grid(row=2, column=1)
    year_field.grid(row=3, column=1)
    todays_day_field.grid(row=1, column=4)
    todays_month_field.grid(row=2, column=4)
    todays_year_field.grid(row=3, column=4)
    resultant_year_field.grid(row=6, column=2)
    resultant_month_field.grid(row=8, column=2)
    resultant_day_field.grid(row=10, column=2)

    # Place the "Calculate Age" button
    Button(window, text="Calculate Age", bg='black', fg='white', command=calculateAge).grid(row=4, column=2)

    # Place the "Clear" button
    Button(window, text="Clear", bg='black', fg='white', command=clear).grid(row=12, column=2)

    # Start the GUI
    window.mainloop()

Output:

tkinter age calculator in Python

In the above Python program, follow the comments to know what is done in each and every step. So, I am not going to describe the code. You can follow the code and read the comments.

I hope you liked the article.

Leave a Reply

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