🎂 Modern Age Calculator - Mini Project in Python for Beginners
Looking for a project using Python that's practical and easy to build? Try this Python mini project – a modern GUI-based Age Calculator app using Tkinter
and tkcalendar
.
🚀 Why This Python Project?
This is one of the best python projects for beginners with a modern interface and accurate output:
- Calculate age in years, months, and days
- Get total time lived in days, weeks, hours, minutes
- Displays countdown to next birthday
- Mobile-friendly window size (360x640)
- Uses modern calendar widget
📦 Requirements
Install tkcalendar
if not already available:
pip install tkcalendar
🧠Age Calculator Program in Python — Source Code
🌐 Age Calculator Using Python
import tkinter as tk
from tkinter import ttk, messagebox
from tkcalendar import Calendar
from datetime import datetime, date, timedelta
import tkinter.font as tkFont
class ModernAgeCalculator:
def __init__(self):
self.app = tk.Tk()
self.setup_window()
self.setup_variables()
self.setup_styles()
self.create_widgets()
def setup_window(self):
self.app.title("🎂 Modern Age Calculator")
self.app.geometry("360x640") # Mobile-friendly size
self.app.configure(bg="#0f172a")
self.app.resizable(False, False)
# Center the window
self.app.update_idletasks()
x = (self.app.winfo_screenwidth() // 2) - (360 // 2)
y = (self.app.winfo_screenheight() // 2) - (640 // 2)
self.app.geometry(f"360x640+{x}+{y}")
def setup_variables(self):
self.months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"]
self.day_var = tk.StringVar(value="1")
self.month_var = tk.StringVar(value="January")
self.year_var = tk.StringVar(value=str(datetime.now().year))
def setup_styles(self):
self.colors = {
'bg_primary': '#0f172a',
'bg_secondary': '#1e293b',
'bg_card': '#334155',
'accent': '#3b82f6',
'accent_hover': '#2563eb',
'success': '#10b981',
'success_hover': '#059669',
'text_primary': '#f1f5f9',
'text_secondary': '#94a3b8',
'danger': '#ef4444',
'warning': '#f59e0b'
}
self.fonts = {
'title': ('Segoe UI', 24, 'bold'),
'subtitle': ('Segoe UI', 12, 'normal'),
'button': ('Segoe UI', 11, 'bold'),
'input': ('Segoe UI', 10, 'normal'),
'result': ('Segoe UI', 11, 'normal'),
'label': ('Segoe UI', 9, 'normal')
}
def create_widgets(self):
main_frame = tk.Frame(self.app, bg=self.colors['bg_primary'])
main_frame.pack(fill='both', expand=True, padx=20, pady=20)
self.create_title_section(main_frame)
self.create_input_section(main_frame)
self.create_button_section(main_frame)
self.create_result_section(main_frame)
self.create_footer(main_frame)
def create_title_section(self, parent):
title_frame = tk.Frame(parent, bg=self.colors['bg_primary'])
title_frame.pack(fill='x', pady=(0, 20))
title_label = tk.Label(title_frame,
text="🎂 Age Calculator",
font=self.fonts['title'],
bg=self.colors['bg_primary'],
fg=self.colors['text_primary'])
title_label.pack()
subtitle_label = tk.Label(title_frame,
text="Calculate your exact age",
font=self.fonts['subtitle'],
bg=self.colors['bg_primary'],
fg=self.colors['text_secondary'])
subtitle_label.pack(pady=(5, 0))
def create_input_section(self, parent):
input_card = tk.Frame(parent, bg=self.colors['bg_secondary'])
input_card.pack(fill='x', pady=(0, 20))
input_content = tk.Frame(input_card, bg=self.colors['bg_secondary'])
input_content.pack(fill='x', padx=15, pady=15)
# Input fields grid
fields_frame = tk.Frame(input_content, bg=self.colors['bg_secondary'])
fields_frame.pack(fill='x')
# Date inputs
inputs_frame = tk.Frame(fields_frame, bg=self.colors['bg_secondary'])
inputs_frame.pack(fill='x', pady=(0, 10))
# Day input
day_frame = tk.Frame(inputs_frame, bg=self.colors['bg_secondary'])
day_frame.pack(side='left', fill='x', expand=True)
tk.Label(day_frame, text="Day", font=self.fonts['label'],
bg=self.colors['bg_secondary'], fg=self.colors['text_secondary']).pack(anchor='w')
day_spinbox = tk.Spinbox(day_frame, from_=1, to=31, textvariable=self.day_var,
font=self.fonts['input'], width=4, bd=0,
bg=self.colors['bg_card'], fg=self.colors['text_primary'],
buttonbackground=self.colors['accent'])
day_spinbox.pack(fill='x', pady=(2, 0), ipady=6)
# Month input
month_frame = tk.Frame(inputs_frame, bg=self.colors['bg_secondary'])
month_frame.pack(side='left', fill='x', expand=True, padx=8)
tk.Label(month_frame, text="Month", font=self.fonts['label'],
bg=self.colors['bg_secondary'], fg=self.colors['text_secondary']).pack(anchor='w')
month_combo = ttk.Combobox(month_frame, values=self.months, textvariable=self.month_var,
font=self.fonts['input'], state="readonly", width=10)
month_combo.pack(fill='x', pady=(2, 0), ipady=6)
# Year input
year_frame = tk.Frame(inputs_frame, bg=self.colors['bg_secondary'])
year_frame.pack(side='left', fill='x', expand=True)
tk.Label(year_frame, text="Year", font=self.fonts['label'],
bg=self.colors['bg_secondary'], fg=self.colors['text_secondary']).pack(anchor='w')
year_spinbox = tk.Spinbox(year_frame, from_=1900, to=datetime.now().year,
textvariable=self.year_var, font=self.fonts['input'],
width=6, bd=0, bg=self.colors['bg_card'],
fg=self.colors['text_primary'],
buttonbackground=self.colors['accent'])
year_spinbox.pack(fill='x', pady=(2, 0), ipady=6)
# Calendar button
calendar_btn = tk.Button(fields_frame, text="📆 Pick Date from Calendar",
command=self.open_calendar, font=self.fonts['button'],
bg=self.colors['accent'], fg='white', bd=0,
padx=12, pady=8, cursor='hand2')
calendar_btn.pack(fill='x', pady=(8, 0))
# Hover effects
calendar_btn.bind("", lambda e: calendar_btn.config(bg=self.colors['accent_hover']))
calendar_btn.bind("", lambda e: calendar_btn.config(bg=self.colors['accent']))
def create_button_section(self, parent):
button_frame = tk.Frame(parent, bg=self.colors['bg_primary'])
button_frame.pack(fill='x', pady=(0, 20))
self.calc_btn = tk.Button(button_frame, text="Calculate My Age",
command=self.calculate_age, font=self.fonts['button'],
bg=self.colors['success'], fg='white', bd=0,
padx=20, pady=10, cursor='hand2')
self.calc_btn.pack(fill='x')
self.calc_btn.bind("", lambda e: self.calc_btn.config(bg=self.colors['success_hover']))
self.calc_btn.bind("", lambda e: self.calc_btn.config(bg=self.colors['success']))
def create_result_section(self, parent):
self.result_card = tk.Frame(parent, bg=self.colors['bg_secondary'])
self.result_card.pack(fill='both', expand=True)
result_content = tk.Frame(self.result_card, bg=self.colors['bg_secondary'])
result_content.pack(fill='both', expand=True, padx=15, pady=15)
# Scrollable area
canvas = tk.Canvas(result_content, bg=self.colors['bg_secondary'], highlightthickness=0)
scrollbar = ttk.Scrollbar(result_content, orient="vertical", command=canvas.yview)
scrollable_frame = tk.Frame(canvas, bg=self.colors['bg_secondary'])
scrollable_frame.bind("", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
self.result_label = tk.Label(scrollable_frame,
text="Enter your birth date and click calculate",
font=self.fonts['result'],
justify='left',
bg=self.colors['bg_secondary'],
fg=self.colors['text_primary'],
wraplength=300)
self.result_label.pack(fill='both', anchor='w')
def create_footer(self, parent):
footer_frame = tk.Frame(parent, bg=self.colors['bg_primary'])
footer_frame.pack(fill='x', side='bottom', pady=(10, 0))
footer_label = tk.Label(footer_frame,
text="Built with ❤️ using Python",
font=('Segoe UI', 8, 'normal'),
bg=self.colors['bg_primary'],
fg=self.colors['text_secondary'])
footer_label.pack()
def open_calendar(self):
def on_date_selected():
selected_date = cal.selection_get()
self.day_var.set(str(selected_date.day))
self.month_var.set(self.months[selected_date.month - 1])
self.year_var.set(str(selected_date.year))
top.destroy()
top = tk.Toplevel(self.app)
top.title("📅 Select Date")
top.geometry("300x340")
top.configure(bg=self.colors['bg_secondary'])
top.resizable(False, False)
# Center the calendar window
top.update_idletasks()
x = (top.winfo_screenwidth() // 2) - (300 // 2)
y = (top.winfo_screenheight() // 2) - (340 // 2)
top.geometry(f"300x340+{x}+{y}")
# Custom calendar styling
style = ttk.Style()
style.theme_use('clam')
style.configure("Calendar.header",
background=self.colors['accent'],
foreground="white",
bordercolor=self.colors['accent'],
relief='flat',
font=('Segoe UI', 10, 'bold'))
style.configure("Calendar.body",
background=self.colors['bg_secondary'],
foreground=self.colors['text_primary'],
selectbackground=self.colors['success'],
font=('Segoe UI', 10))
style.map("Calendar.body",
background=[('selected', self.colors['success'])])
cal = Calendar(top, selectmode='day',
year=datetime.now().year,
month=datetime.now().month,
day=datetime.now().day,
background=self.colors['bg_secondary'],
foreground=self.colors['text_primary'],
headersbackground=self.colors['accent'],
normalbackground=self.colors['bg_secondary'],
weekendbackground='#2d3748',
bordercolor=self.colors['accent'],
selectbackground=self.colors['success'],
showweeknumbers=False)
cal.pack(pady=15, padx=15, fill='both', expand=True)
select_btn = tk.Button(top, text="✅ Select", command=on_date_selected,
bg=self.colors['success'], fg="white",
font=("Segoe UI", 10, "bold"), bd=0,
padx=15, pady=6, relief="flat", cursor="hand2")
select_btn.pack(pady=(0, 15))
select_btn.bind("", lambda e: select_btn.config(bg=self.colors['success_hover']))
select_btn.bind("", lambda e: select_btn.config(bg=self.colors['success']))
def calculate_age(self):
try:
day = int(self.day_var.get())
month = self.months.index(self.month_var.get()) + 1
year = int(self.year_var.get())
birth_date = date(year, month, day)
today = date.today()
if birth_date > today:
messagebox.showerror("❌ Error", "Birth date cannot be in the future!")
return
delta = today - birth_date
years = today.year - year
months = today.month - month
days = today.day - day
if days < 0:
months -= 1
prev_month = today.replace(day=1) - timedelta(days=1)
days += prev_month.day
if months < 0:
years -= 1
months += 12
result = f"""🎂 Exact Age:
{years} years, {months} months, {days} days
📊 Statistics:
• Months: {(years*12)+months:,}
• Weeks: {delta.days//7:,}
• Days: {delta.days:,}
• Hours: {delta.days*24:,}
• Minutes: {delta.days*24*60:,}
🎉 Next Birthday: {self.get_next_birthday(birth_date)}"""
self.result_label.config(text=result)
except ValueError:
messagebox.showerror("❌ Error", "Invalid date values!")
except Exception as e:
messagebox.showerror("❌ Error", f"Error: {str(e)}")
def get_next_birthday(self, birth_date):
today = date.today()
next_bd = birth_date.replace(year=today.year)
if next_bd < today:
next_bd = next_bd.replace(year=today.year+1)
return f"{(next_bd - today).days} days"
def run(self):
self.app.mainloop()
if __name__ == "__main__":
ModernAgeCalculator().run()
🔍 Output Preview
📁 Perfect Python Project for Beginners
This app is ideal if you're looking for:
- Beginner Python projects
- Python mini projects with GUI
- Simple Python projects for practice
- Python project ideas for portfolios
🧠 What You’ll Learn
- Building interfaces with
Tkinter
- Using
Calendar
widgets - Handling dates with
datetime
andtimedelta
- Improving GUI styling and layout
📥 How to Run This Python Project
- Save the code in a file named
age_calculator.py
- Open your terminal or command prompt
- Run the program:
python age_calculator.py
- Pick your birthdate and click “Calculate My Age”
📊 Output Example
After calculation, it shows:
- Exact age: 22 years, 4 months, 15 days
- Days lived: 8,172
- Next birthday: 137 days left
- Bonus: time lived in hours, weeks, and minutes
✅ Conclusion
This simple project in Python is a great hands-on exercise if you’re building a list of python beginner projects. It covers GUI, date handling, and real-time calculations — all in under 300 lines of code.
Whether it’s your first mini project in Python or you're exploring more simple projects in Python, this age calculator is a fantastic start.