|
| 1 | +# import libraries |
| 2 | +from tkinter import * |
| 3 | +from datetime import date |
| 4 | + |
| 5 | +# initialized window |
| 6 | +root = Tk() |
| 7 | +root.geometry('280x300') |
| 8 | +root.resizable(0,0) |
| 9 | +root.title('Age Calculator') |
| 10 | +statement = Label(root) |
| 11 | + |
| 12 | +# defining the function for calculating age |
| 13 | +def ageCalc(): |
| 14 | + global statement |
| 15 | + statement.destroy() |
| 16 | + today = date.today() |
| 17 | + birthDate = date(int(yearEntry.get()), int(monthEntry.get()), int(dayEntry.get())) |
| 18 | + age = today.year - birthDate.year |
| 19 | + if today.month < birthDate.month or today.month == birthDate.month and today.day < birthDate.day: |
| 20 | + age -= 1 |
| 21 | + statement = Label(text=f"{nameValue.get()}'s age is {age}.") |
| 22 | + statement.grid(row=6, column=1, pady=15) |
| 23 | + |
| 24 | +# creating a label for person's name to display |
| 25 | +l1 = Label(text = "Name: ") |
| 26 | +l1.grid(row=1, column=0) |
| 27 | +nameValue = StringVar() |
| 28 | + |
| 29 | +# creating a entry box for input |
| 30 | +nameEntry = Entry(root, textvariable=nameValue) |
| 31 | +nameEntry.grid(row=1, column=1, padx=10, pady=10) |
| 32 | + |
| 33 | +# label for year in which user was born |
| 34 | +l2 = Label(text = "Year: ") |
| 35 | +l2.grid(row=2, column=0) |
| 36 | +yearValue = StringVar() |
| 37 | +yearEntry = Entry(root, textvariable=yearValue) |
| 38 | +yearEntry.grid(row=2, column=1, padx=10, pady=10) |
| 39 | + |
| 40 | +# label for month in which user was born |
| 41 | +l3 = Label(text = "Month: ") |
| 42 | +l3.grid(row=3, column=0) |
| 43 | +monthValue = StringVar() |
| 44 | +monthEntry = Entry(root, textvariable=monthValue) |
| 45 | +monthEntry.grid(row=3, column=1, padx=10, pady=10) |
| 46 | + |
| 47 | +# label for day/date on which user was born |
| 48 | +l4 = Label(text = "Day: ") |
| 49 | +l4.grid(row=4, column=0) |
| 50 | +dayValue = StringVar() |
| 51 | +dayEntry = Entry(root, textvariable=dayValue) |
| 52 | +dayEntry.grid(row=4, column=1, padx=10, pady=10) |
| 53 | + |
| 54 | +# create a button for calculating age |
| 55 | +button = Button(text="Calculate age", command=ageCalc) |
| 56 | +button.grid(row=5, column=1) |
| 57 | + |
| 58 | +# infinite loop to run program |
| 59 | +root.mainloop() |
0 commit comments