问题:如何在这个程序中创建一个函数,使变量year_of_birth和year_present在一起(年龄计算器).&l


from tkinter import *
def age_calculator():
window=Tk()
window.title("Age Calculator")
label_one=Label(window,text="Welcome to Age Calculator",fg="green")
label_one.pack()
year_of_birth=Entry(window,width=5,bd=4)
year_of_birth.place(x=210,y=100)
label_two=Label(window,text="Year of Birth",fg="purple")
label_two.place(x=200,y=70) 
year_present=Entry(window,width=5,bd=4)
year_present.place(x=470,y=100)
label_three=Label(window,text="Year in Present",fg="red")
label_three.place(x=450,y=70)
l4=Label(window,text="=")
l4.place(x=670,y=100)
button1=Button(window,text="Calculate",fg="red",bg="green",command=mainCalcu)
button1.place(x=800,y=100)
window.mainloop()
age_calculator()

所以我尝试使用许多方法,我需要一个def函数,它可以减去year_present除以year_of_birth,输出应该显示。

我找到了一个方法。如果您想要更改消息,请在"更改下面的输出"注释下面的行中更改。输出变量是输出(因此得名output)

from tkinter import *
window = Tk()
window.title("Age Calculator")
label_one = Label(window,text="Welcome to Age Calculator",fg="green")
label_one.pack()
year_of_birth = Entry(window,width=5,bd=4)
year_of_birth.place(x=210,y=100)
label_two = Label(window,text="Year of Birth",fg="purple")
label_two.place(x=200,y=70) 
year_present = Entry(window,width=5,bd=4)
year_present.place(x=470,y=100)
label_three = Label(window,text="Year in Present",fg="red")
label_three.place(x=450,y=70)
l4 = Label(window,text="=")
l4.place(x=670,y=100)

def mainCalcu(year_of_birth, year_present):
string1 = year_of_birth.get()
string2 = year_present.get()
calcedVal = int(string2) - int(string1)
# The variable 'calcedVal' is the variable you can use in your output
# Change output below
output = Label(window, text = "You are " + str(calcedVal) + " years old!").place(x=670,y=150)
button1 = Button(window,text="Calculate",fg="red",bg="green", command = lambda: mainCalcu(year_of_birth, year_present))
button1.place(x=800,y=100)
window.mainloop()

最新更新