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

how do i make my program work with tkinter?

所以基本上我试图让我的 tkinter gui 与我的 'how many days you have lived' 程序一起工作,我试图让它工作但它一直崩溃。我是编程新手,我最近开始使用 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 应用程序混合使用。控制台输入将等待您输入一些内容。如果没有控制台,您的程序将冻结。

还了解 event-driven 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()