|
| 1 | +import tkinter as tk |
| 2 | +from tkinter import messagebox |
| 3 | +from datetime import datetime |
| 4 | + |
| 5 | +# Function to calculate age |
| 6 | +def calculate_age(): |
| 7 | + try: |
| 8 | + year = int(entry_year.get()) |
| 9 | + month = int(entry_month.get()) |
| 10 | + day = int(entry_day.get()) |
| 11 | + today = datetime.today() |
| 12 | + birth_date = datetime(year, month, day) |
| 13 | + age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day)) |
| 14 | + messagebox.showinfo("Age Calculator", f"Hello, {entry_name.get()}!\nYou are {age} years old.") |
| 15 | + except ValueError: |
| 16 | + messagebox.showerror("Input Error", "Please enter valid numerical values for year, month, and day.") |
| 17 | + |
| 18 | +# Setting up the GUI |
| 19 | +root = tk.Tk() |
| 20 | +root.title("Age Calculator") |
| 21 | + |
| 22 | +# Labels |
| 23 | +label_name = tk.Label(root, text="Name:") |
| 24 | +label_name.grid(row=0, column=0, padx=10, pady=10) |
| 25 | + |
| 26 | +label_year = tk.Label(root, text="Year of Birth:") |
| 27 | +label_year.grid(row=1, column=0, padx=10, pady=10) |
| 28 | + |
| 29 | +label_month = tk.Label(root, text="Month of Birth:") |
| 30 | +label_month.grid(row=2, column=0, padx=10, pady=10) |
| 31 | + |
| 32 | +label_day = tk.Label(root, text="Day of Birth:") |
| 33 | +label_day.grid(row=3, column=0, padx=10, pady=10) |
| 34 | + |
| 35 | +# Entry widgets |
| 36 | +entry_name = tk.Entry(root) |
| 37 | +entry_name.grid(row=0, column=1, padx=10, pady=10) |
| 38 | + |
| 39 | +entry_year = tk.Entry(root) |
| 40 | +entry_year.grid(row=1, column=1, padx=10, pady=10) |
| 41 | + |
| 42 | +entry_month = tk.Entry(root) |
| 43 | +entry_month.grid(row=2, column=1, padx=10, pady=10) |
| 44 | + |
| 45 | +entry_day = tk.Entry(root) |
| 46 | +entry_day.grid(row=3, column=1, padx=10, pady=10) |
| 47 | + |
| 48 | +# Button to calculate age |
| 49 | +button_calculate = tk.Button(root, text="Calculate Age", command=calculate_age) |
| 50 | +button_calculate.grid(row=4, column=0, columnspan=2, pady=20) |
| 51 | + |
| 52 | +# Run the GUI |
| 53 | +root.mainloop() |
0 commit comments