so basically im trying to make my tkinter gui work with my 'how many days you have lived' program , i tried to make it work but it kept crashing. Im new to programming i started recently with python , id would be happy if you guys could help me.
from tkinter import Tk
from datetime import datetime
root = Tk()
root.geometry('300x300')
root.title('How many days ?')
root.resizable(False, False)
inputdate = tk.Label(text= "Type in your date")
inputdate.place(x= 90, y= 30)
# date entry (type your date)
inputdate_entry =tk.Entry(width=11)
inputdate_entry.place(x= 90, y= 60)
# calculates how many days you have lived , by pressing the calculate button
enter_btn = tk.Button(text='Calculate',width= 8)
enter_btn.place(x= 90, y= 180)
# here comes output and shows how many days you have lived
output_entry =tk.Entry(width=11)
output_entry.place(x= 90, y= 220)
# the program that calculates hoe many days you have lived
birth_date = input()
birth_day = int(birth_date.split('/')[0])
birth_month = int(birth_date.split('/')[1])
birth_year = int(birth_date.split('/')[2])
actual = datetime.now() - datetime(year=birth_year, month=birth_month, day=birth_day)
print(actual)
root.mainloop()
CodePudding user response:
You should not mix console input input()
with GUI application. The console input will wait for you to input something. If there is no console, your program will freeze.
Also understand event-driven programming that tkinter is based on. You need to do the calculation in a callback triggered by the button.
Below is the modified code:
import tkinter as tk
from datetime import datetime
# function to be called when the Calculate button is clicked
def calculate():
try:
# get the input date in DD/MM/YYYY format
birth_date = inputdate_entry.get()
# split the date into day, month and year
birth_day, birth_month, birth_year = birth_date.split('/')
# calculate the time difference from the input date to now
actual = datetime.now() - datetime(year=int(birth_year), month=int(birth_month), day=int(birth_day))
# show the number of days calculated
output_entry.delete(0, tk.END)
output_entry.insert(0, f'{actual.days} days')
except Exception as ex:
print(ex)
root = tk.Tk()
root.geometry('300x300')
root.title('How many days ?')
root.resizable(False, False)
inputdate = tk.Label(text="Type in your date (dd/mm/yyyy)")
inputdate.place(x=90, y=30)
# date entry (type your date)
inputdate_entry = tk.Entry(width=11)
inputdate_entry.place(x=90, y=60)
# calculates how many days you have lived , by pressing the calculate button
enter_btn = tk.Button(text='Calculate', command=calculate) # call calculate()
enter_btn.place(x=90, y=180)
# here comes output and shows how many days you have lived
output_entry = tk.Entry(width=11)
output_entry.place(x=90, y=220)
root.mainloop()