如何使我的程序与tkinter一起工作



所以基本上我试图让我的tkinter-gui与我的"你活了多少天"程序一起工作,我试图让它工作,但它一直崩溃。我最近刚开始用python编程,如果你们能帮助我,我会很高兴。

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()

您不应该将控制台输入input()与GUI应用程序混合使用。控制台输入将等待您输入内容。如果没有控制台,您的程序将冻结。

还要理解tkinter所基于的事件驱动编程。您需要在按钮触发的回调中进行计算。

以下是修改后的代码:

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()

最新更新