0

I am new to programming in python, and I want to create simple app for calculating your age based on the user input. I am using the 'datetime' module, and I found example of the program running in the terminal, but I don't know tow to link the entry box with the button using tkinter. This is the link from the code sample I am using and want to recreate it in tkinter.

import tkinter as tk
from datetime import date

def CheckAge():
global result # to return calculation
result = str(entry.get())

today = date.today()
#Convert user input into a date
dob_data = result.split("/")
dobDay = int(dob_data[0])
dobMonth = int(dob_data[1])
dobYear = int(dob_data[2])
dob = date(dobYear,dobMonth,dobDay)

#Calculate number of days lived
numberOfDays = (today - dob).days 

#Convert this into whole years to display the age
age = numberOfDays // 365
label=tk.Label(root, "You are "+str(age) +" years old", command=CheckAge)
label.pack()
print("You are " + str(age) + " years old.")

result = 0
root = tk.Tk()

entry = tk.Entry(root)
entry.pack()

button = tk.Button(root, text="Calculate", command=CheckAge)
button.pack()

root.mainloop()

At the end of executing this code I get this error message:

dobDay = int(dob_data[0])
ValueError: invalid literal for int() with base 10: ''

As mentioned, I am beginner and I am using multiple code samples from online forums.

1 Answers1

0

first of all, label does NOT have a command. Secondly, you need to add the attribute "text" to the label. So, here is the modified version of your code:

import tkinter as tk
from datetime import date

def CheckAge():
   global result # to return calculation
   result = str(entry.get())

   today = date.today()
   #Convert user input into a date
   dob_data = result.split("/")

   dobDay = int(dob_data[0])
   dobMonth = int(dob_data[1])
   dobYear = int(dob_data[2])
   dob = date(dobYear,dobMonth,dobDay)

   #Calculate number of days lived
   numberOfDays = (today - dob).days 

   #Convert this into whole years to display the age
   age = numberOfDays // 365

   label=tk.Label(root, text="You are "+str(age) +" years old")
   label.pack()
   print("You are " + str(age) + " years old.")

result = 0
root = tk.Tk()

entry = tk.Entry(root)
entry.pack()

button = tk.Button(root, text="Calculate", command=CheckAge)
button.pack()

root.mainloop()

With these little modifications you should be able to get the result you wanted it.

Baraa
  • 176
  • 8