Age Calculator using PyQt

In today's digital age, creating user-friendly desktop applications with graphical user interfaces (GUI) has become increasingly important. Python, a versatile and popular programming language, offers a multitude of frameworks and libraries to develop powerful applications. PyQt, a Python binding for the Qt framework, is one such library that empowers developers to create robust and visually appealing desktop applications.

Age calculators are commonly used tools that allow users to determine their current age based on their birthdate. By leveraging the capabilities of PyQt, we can create an intuitive and efficient age calculator application that provides a seamless user experience.

Setting up the Project

Before we start building our age calculator application using PyQt, we need to ensure that we have the necessary prerequisites installed. Firstly, make sure you have Python 3.x installed on your system. You can download the latest version of Python from the official Python website (python.org).

Once Python is installed, we need to install the PyQt5 library. Open your command-line interface and run the following command ?

pip install PyQt5

This will install the PyQt5 library and its dependencies, enabling us to create our GUI application.

Complete Age Calculator Implementation

Let's create a complete age calculator application. First, we need to import the necessary modules and classes from PyQt5 ?

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QDateEdit, QPushButton, QMessageBox
from PyQt5.QtCore import Qt, QDate

class AgeCalculator(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Age Calculator")
        self.setGeometry(300, 300, 300, 200)
        self.setup_ui()

    def setup_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)

        # Create label
        birthdate_label = QLabel("Enter your birthdate:")
        layout.addWidget(birthdate_label)

        # Create date picker
        self.birthdate_edit = QDateEdit(calendarPopup=True)
        self.birthdate_edit.setMaximumDate(QDate.currentDate())
        self.birthdate_edit.setDate(QDate(2000, 1, 1))  # Default date
        layout.addWidget(self.birthdate_edit)

        # Create calculate button
        calculate_button = QPushButton("Calculate Age")
        calculate_button.clicked.connect(self.calculate_age)
        layout.addWidget(calculate_button)

    def calculate_age(self):
        birthdate = self.birthdate_edit.date()
        current_date = QDate.currentDate()

        # Calculate years, months, and days
        age_years = current_date.year() - birthdate.year()
        age_months = current_date.month() - birthdate.month()
        age_days = current_date.day() - birthdate.day()

        # Adjust for negative days
        if age_days < 0:
            age_months -= 1
            age_days += birthdate.daysInMonth()

        # Adjust for negative months
        if age_months < 0:
            age_years -= 1
            age_months += 12

        # Display result
        age_text = f"You are {age_years} years, {age_months} months, and {age_days} days old."
        QMessageBox.information(self, "Age Calculation", age_text)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    calculator = AgeCalculator()
    calculator.show()
    sys.exit(app.exec())

How It Works

The application consists of several key components:

AgeCalculator Class: Inherits from QWidget and serves as the main window. The constructor sets the window title, size, and calls the UI setup method.

User Interface Setup: The setup_ui() method creates a vertical layout with a label, date picker widget, and calculate button. The date picker is configured with a calendar popup and restricts the maximum date to today.

Age Calculation Logic: The calculate_age() method retrieves the selected birthdate and current date, then calculates the difference in years, months, and days. It handles edge cases where days or months might be negative by adjusting the calculations accordingly.

Key Features

  • Calendar Popup: Users can easily select dates using an interactive calendar
  • Date Validation: Prevents selection of future dates
  • Precise Calculation: Calculates age in years, months, and days
  • User-Friendly Display: Shows results in a clear message box

Running the Application

Save the code in a file named age_calculator.py and run it using ?

python age_calculator.py

The application window will appear with a date picker set to January 1, 2000 by default. Select your birthdate and click "Calculate Age" to see your exact age in years, months, and days.

Conclusion

This PyQt5 age calculator demonstrates how to create functional desktop applications with intuitive user interfaces. The combination of date selection widgets, event handling, and message dialogs provides a solid foundation for more complex GUI applications using PyQt.

Updated on: 2026-03-27T12:38:43+05:30

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements