Movatterモバイル変換


[0]ホーム

URL:


How to Make an Age Calculator in Python

Learn how you to build an age calculator that calculates your age based on your birthday using Tkinter and datetime library in Python.
  · 12 min read · Updated mar 2023 ·GUI Programming

Step up your coding game withAI-powered Code Explainer. Get insights like never before!

If you have fancied the idea of building your own age calculator app using Python, then you are at the right place because this article is just for you.

Before we dive deeper into this article, let us first understand what an age calculator app is; this app calculates the user's age using their birth date (day, month, and year).

This article has been split into two sections. In the first section, we will build a command line version, and finally, in the second section, we will make a GUI version of the app. We will build all these from the ground up.

Here is the table of contents:

Setting up the Environment

First things first, let us set up the environment, create two new Python files and call themage_calculator_cli.py andage_calculator_ui.py:

You can call them anything per your preference; make sure the file names are meaningful.

Related:How to Make a Calculator with Tkinter in Python.

Building the Command Line Version

Now that the environment is all set, open theage_calculator_cli.py file, and do the following import:

from datetime import date

Here we are importingdate fromdatetime, this module provides several functions and classes for handling dates and times.

We will now create a function for calculating the age; we will call itcalculate_age(). Just below the import, paste these lines of code:

# defining the for calculating the age, the function takes daydef calculate_age(day, month, year):    # we are getting the current date using the today()    today = date.today()    # convering year, month and day into birthdate    birthdate = date(year, month, day)    # calculating the age     age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))    # return the age value    return age

In the above function, we are passing three arguments to the function,date,month, andyear, we will get these arguments from the user.

Inside the function, we are getting the current date fromdatetime module using thetoday() function. After that, we create abirthdate variable using thedate() function; it takes ayear,month, andday as arguments. From there, we are now calculating theage by doing some subtractions, the code:

((today.month, today.day) < (birthdate.month, birthdate.day))

Checks if the day or month of the variabletoday precedes the day or month of thebirthdate variable, the return value is a boolean value, and finally, we return the calculatedage.

Now we need to get theday,month, andyear from the user, just after the function definition, paste these lines of code:

# the try/except block# the try will execute if there are no exceptionstry:    # we are getting day, month, and year using input() function    day = input('Enter day:')    month = input('Enter month:')    year = input('Enter year:')    # creating a variable called age_result and we are also calling the claculate_age function    age_result = calculate_age(int(day), int(month), int(year))    print(f'You are {age_result} years old')    # the except will catch all errorsexcept:    print(f'Failed to calculate age, either day or month or year is invalid')

Here we have atry/except block, inside thetry statement, we have code for getting data from the user; this is done using theinput() function, and with that user data, we calculate the age via the function call. If the code execution encounters any errors, theexcept statement will come to the rescue.

To test the program, use the following:

$ python age_calculator_cli.py

The output is as follows if you enter valid data:

Enter day:12Enter month:10Enter year:2000You are 21 years old

The program is running as expected, rerun it, but this time, let's enter invalid data. The output will be as below:

Enter day:-1Enter month:hEnter year:0.5Failed to calculate age, either day or month or year is invalid

We have successfully created the command line version of the age calculator!

Building the GUI Version

In this section, we will now focus on building the Tkinter version of our age calculator. Its functionality is not different from the command line version. The only difference is that the Tkinter version app has a user interface that allows users to enter data. This is what we are going to build at the end of this section:

So without further ado, let us start building the app.

Designing the User Interface

Before everything else, let us start by designing the user interface, do the following necessary imports as follows in theage_calculator_ui.py:

from tkinter import *from tkinter import ttkfrom tkinter.messagebox import showerrorfrom datetime import date

Here is what the imports mean; starting with the first one, we are importing everything fromtkinter. To do this, we use an asterisk or a wildcard. After that, we importttk fromtkinter,ttk is for styling widgets (labels, buttons, entries, etc.).

We are also importing theshowerror message box for displaying error messages to the user fromtkinter.messagebox. Finally, we are importing thedatetime module.

We will create the window just after the imports. Paste these lines of code:

# creating the main windowwindow = Tk()# the title for the windowwindow.title('Age Calculator')# the dimensions and position of the windodwwindow.geometry('500x260+430+300')# making the window nonresizabalewindow.resizable(height=FALSE, width=FALSE)# runs the window infinitely until uses closes itwindow.mainloop()

For the sake of being on the same page, let us break the code a bit. Firstly, we are creating the main window using theTk() function that comes with Tkinter, then we give the window the title using thetitle() function, we are then defining the dimensions (500x260) and the position (430+300) for the window using thegeometry() function, to make the window non-resizable, we are using theresizable() function withheight andwidth set toFALSE.

Running the program, you will get the following:

After creating the window, we now need to make the container for all the widgets; we will use aCanvas widget. ThisCanvas will be inside the main window, and it will take up theheight andwidth like this:

So just after:

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

Paste this code:

# the canvas to contain all the widgetscanvas = Canvas(window, width=500, height=400)canvas.pack()

We are creating a canvas using theCanvas() function, and placing it inside the main window. For the size of the canvas, we are usingwidth andheight.

Now we need to create widgets that will be placed inside the created canvas, but before making the widgets, let us create their styles; just below the canvas definition, add these lines of code:

# ttk styles for the labelslabel_style = ttk.Style()label_style.configure('TLabel', foreground='#000000', font=('OCR A Extended', 14))# ttk styles for the buttonbutton_style = ttk.Style()button_style.configure('TButton', foreground='#000000', font=('DotumChe', 16))# ttk styles for the entriesentry_style = ttk.Style()entry_style.configure('TEntry', font=('Dotum', 15))

In the code above, we are creating styles for the widgets; we are using thettk module for this.

We are building a style object usingttk.Style() function, so to add styles to the object, we will use theconfigure() function, this function takes the style name (TLabel,TButton, orTEntry),foreground, andfont() as some of its arguments.

In our widgets, we will use the style names to refer to or point to the styles we want. Now that the styles are taken care of, we will create the widgets. Let’s start with the label for displaying the large text. Below the styles, add this code:

# the label for displaying the big textbig_label = Label(window, text='AGE CALCULATOR', font=('OCR A Extended', 25))# placing the big label inside the canvascanvas.create_window(245, 40, window=big_label)

The code creates a label usingLabel(), we are passingwindow,text, andfont as arguments, something to note here, this label has independent styles; it is not using the styles we have created.

Below the label, we are adding it to the canvas using thecreate_window() function, this function takes two integers (245 and 40) and awindow as arguments, the first integer positions the labelhorizontally, and the second integer positions itvertically.

Running the program, you will get this:

So far, so good. Our app is taking shape; now let us create the remaining widgets; add this code below thebig_label:

# label and entry for the dayday_label = ttk.Label(window, text='Day:', style='TLabel')day_entry = ttk.Entry(window, width=15, style='TEntry')# label and entry for the monthmonth_label = ttk.Label(window, text='Month:', style='TLabel')month_entry = ttk.Entry(window, width=15, style='TEntry')# label and entry for the yearyear_label = ttk.Label(window, text='Year:', style='TLabel')year_entry = ttk.Entry(window, width=15, style='TEntry')# the button calculate_button = ttk.Button(window, text='Calculate Age', style='TButton', command=calculate_age)# label for display the calculated ageage_result = ttk.Label(window, text='', style='TLabel')# adding the day label and entry inside the canvascanvas.create_window(114, 100, window=day_label)canvas.create_window(130, 130, window=day_entry)# adding the month label and entry inside the canvascanvas.create_window(250, 100, window=month_label)canvas.create_window(245, 130, window=month_entry)# adding the year label and entry inside the canvascanvas.create_window(350, 100, window=year_label)canvas.create_window(360, 130, window=year_entry)# adding the age_result and entry inside the canvascanvas.create_window(245, 180, window=age_result)# adding the calculate button inside the canvascanvas.create_window(245, 220, window=calculate_button)

With this code snippet, we are creating the following widgets:

  • Labels for displayingDay,Month,Year, andage_result text:
    • day_label
    • month_label
    • year_label
    • age_result, this is empty for now.
  • Entries for capturingday,month andyear values:
    • day_entry
    • month_entry
    • year_entry
  • A button:
    • calculate_button

All these widgets arettk widgets, so to style them, we are passing thestyle argument, for example, the button widget uses theTButton style that we created.

Testing the app, we get the following:

Congratulations on successfully designing the app’s user interface!

Implementing the Age Calculation Functionality

Now that the user interface is taken care of, let us make the app reactive. The app should be able to get data from the user and calculate the age. To do this, we will create a function just below the imports calledcalculate_age(), paste this code:

# the function for calculating the agedef calculate_age():    # the try/except block    try:        # getting current date        today = date.today()        # getting day from the day entry        day = int(day_entry.get())        # # getting month from the month entry        month = int(month_entry.get())        # getting year from the year entry        year = int(year_entry.get())        # creating a date object        birthdate = date(year, month, day)        # calculating the age        age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))        # displaying the age using the age result label        age_result.config(text='You are ' + str(age) + ' years old')    # if an error occurs the showerror window will pop up    except:        showerror(title='Error', message='An error occurred while trying to ' \                    'calculate age\nThe following could ' \                    'be the causes:\n->Invalid input data\n->An empty field/fields\n'\                     'Make sure you enter valid data and fill all the fields')

This function is all the same as the one we used in the command line version of the app; the only difference here is that in thetry statement, we are getting theday,month, andyear from the entries using theget() function and also in theexcept statement, all errors that the app will catch will be displayed on theshowerror popup window.

Nothing happens if you run the app, enter valid data in the entries, and click the button. The reason is that we have not linked thecalculate_age() function with the button. We want the function to be triggered once the user clicks the button. To do this, we will use the command argument that comes with the button widget, edit thecalculate_age button code and make it look like this:

calculate_button = ttk.Button(window, text='Calculate Age', style='TButton', command=calculate_age)

Rerun the app, re-enter the valid data, and you will get the following:

What if the user enters invalid data or leaves one or all the entries empty and clicks the button? The output will be this:

This means that the app is working perfectly!

Conclusion

This article showed you how to create an age calculator using Python. We walked you through building two versions of the age calculator app, the command line and the Tkinter version. We hope you will use the knowledge you acquired from this article in your future projects!

You can get the complete codehere.

Here are some related apps we've built in other tutorials:

Happy coding ♥

Why juggle between languages when you can convert? Check out ourCode Converter. Try it out today!

View Full Code Build My Python Code
Sharing is caring!



Read Also


How to Build a Spreadsheet App with Tkinter in Python
How to Detect Gender by Name using Tkinter in Python
How to Build a GUI Currency Converter using 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-2025 Movatter.jp