所以基本上我試圖讓我的 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()
uj5u.com熱心網友回復:
您不應將控制臺輸入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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441021.html
