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.

With the prerequisites in place, we are ready to proceed to the next steps and start building our age calculator using PyQt. In the upcoming sections, we will create the application window, implement the age calculation logic, and run the application to test its functionality.

Creating the Application Window

The first step in building our age calculator is to create the application window. In PyQt, the window is represented by a class that inherits from the QWidget class. This class provides the foundation for creating and managing windows in PyQt applications.

Let's begin by creating a new Python file for our project, which we'll name age_calculator.py. Open your preferred text editor or integrated development environment (IDE) and create a new file with that name.

To start, we need to import the necessary modules and classes from the PyQt5 library. Add the following code at the beginning of your age_calculator.py file 

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

In this code snippet, we import sys for system-related operations, QApplication and QWidget for creating the application window, QLabel for displaying text, QVBoxLayout for organizing the layout vertically, QDateEdit for selecting the birthdate, QPushButton for creating buttons, and QMessageBox for displaying messages.

Next, we'll define the AgeCalculator class, which will serve as our application window. Add the following code below the import statements 

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

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

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

      birthdate_edit = QDateEdit(calendarPopup=True)
      birthdate_edit.setMaximumDate(QDate.currentDate())
      layout.addWidget(birthdate_edit)

      calculate_button = QPushButton("Calculate Age")
      calculate_button.clicked.connect(self.calculate_age)
      layout.addWidget(calculate_button)

In this code snippet, we define the AgeCalculator class as a subclass of QWidget. The constructor method __init__() is called when an instance of the class is created. Inside the constructor, we set the window title using self.setWindowTitle(). We also call the setup_ui() method, which will be responsible for setting up the user interface of our application.

In the setup_ui() method, we create a vertical layout using QVBoxLayout and set it as the layout for our window using self.setLayout(). We then create a QLabel widget to display the "Enter your birthdate" text, add it to the layout using layout.addWidget(), and create a QDateEdit widget to allow users to select their birthdate. We enable the calendar popup using calendarPopup=True and set the maximum selectable date to the current date using birthdate_edit.setMaximumDate(QDate.currentDate()). Finally, we create a "Calculate Age" button using QPushButton, connect its clicked signal to the calculate_age() method using calculate_button.clicked.connect(), and add it to the layout.

Calculating the Age

Now that we have created the application window, let's implement the logic for calculating the age based on the selected birthdate. When the user clicks the "Calculate Age" button, we will retrieve the birthdate, calculate the age, and display the result.

Inside the AgeCalculator class, add the following code −

def calculate_age(self):
   birthdate = self.sender().parent().findChild(QDateEdit).date()
   current_date = QDate.currentDate()

   age_years = current_date.year() - birthdate.year()
   age_months = current_date.month() - birthdate.month()
   age_days = current_date.day() - birthdate.day()

   if age_days < 0:
      age_months -= 1
      age_days += birthdate.daysInMonth()

   if age_months < 0:
      age_years -= 1
      age_months += 12

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

In this code snippet, we define the calculate_age() method, which will be called when the "Calculate Age" button is clicked. Inside the method, we retrieve the birthdate from the QDateEdit widget using the sender() method. The sender() method returns the object that emitted the signal, which in this case is the "Calculate Age" button. We access its parent widget using parent() and find the QDateEdit widget using findChild(QDateEdit). We then retrieve the selected date using .date().

We also get the current date using QDate.currentDate(). With the birthdate and current date, we calculate the difference in years, months, and days using simple arithmetic operations. If the number of days is negative, we adjust the number of months and add the number of days in the birth month. Similarly, if the number of months is negative, we subtract one year and add 12 months.

Running the Application

To run the age calculator application, we need to create an instance of the QApplication class, instantiate the AgeCalculator class, show the window, and start the application event loop.

At the end of your age_calculator.py file, add the following code 

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

In this code snippet, we check if the current module is the main module using __name__ == "__main__". This allows us to ensure that the following code is only executed when the script is run directly, rather than when it is imported as a module.

Inside the conditional block, we create an instance of QApplication named app. We then instantiate the AgeCalculator class and assign it to the calculator variable. We call show() on the calculator object to display the window. Finally, we start the application event loop by calling app.exec(). The sys.exit() call ensures a clean exit when the application is closed.

Save your file and run it using the command python age_calculator.py. You should see the age calculator window appear.

Conclusion

Here, we have explored the process of creating an age calculator application using PyQt. We started by setting up the project and importing the necessary libraries. We then created the application window, implemented the age calculation logic, and ran the application to test its functionality.

By leveraging the power of PyQt, we have built a user-friendly age calculator that provides an intuitive and efficient way for users to determine their current age based on their birthdate. This tutorial serves as a solid foundation for your journey into GUI application development using PyQt, and you can apply the concepts learned here to build a wide range of other desktop applications.

Updated on: 16-Aug-2023

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements