所以我正在制作一个温度转换器,我只是无法得到华氏温度到摄氏温度的计算结果。它适用于从摄氏温度到华氏温度,但它不会转换为另一种方式。我不知道是什么问题导致这个我尝试了intvars和stringvars但似乎没有解决这个问题,我也尝试了diff if语句,但它只是不能从fah转换为cel。有人可以帮助我,告诉我什么是错的。这就是我所拥有的:
from Tkinter import*
def convert():
celTemp = celTempVar.get()
fahTemp = fahTempVar.get()
if celTempVar.get() != 0.0:
celToFah = (celTemp * 9/5 + 32)
print celToFah
fahTempVar.set(celToFah)
elif fahTempVar.get() != 0.0:
fahToCel = ((fahTemp - 32) * (5/9))
print fahToCel
celTempVar.set(fahToCel)
def reset():
top = Toplevel(padx=50, pady=50)
top.grid()
message = Label(top, text = "Reset Complete")
button = Button(top, text="OK", command=top.destroy)
message.grid(row = 0, padx = 5, pady = 5)
button.grid(row = 1, ipadx = 10, ipady = 10, padx = 5, pady = 5)
fahTempVar.set(int(0))
celTempVar.set(int(0))
###MAIN###
root = Tk()
root.title("Temperature Converter")
mainframe = Frame(root)
mainframe.grid()
celTempVar = IntVar()
celTempVar.set(int(0))
fahTempVar = IntVar()
fahTempVar.set(int(0))
titleLabel = Label (mainframe, text = "Celcius/Fahrenheit Temperature", font = ("Arial", 20, "bold"), justify = CENTER)
titleLabel.grid(row = 1, column = 1, columnspan = 3, pady = 10, padx = 20)
celLabel = Label (mainframe, text = "Celcius: ", font = ("Arial", 16), fg = "red")
celLabel.grid(row = 2, column = 1, pady = 10, sticky = NW)
fahLabel = Label (mainframe, text = "Fahrenheit: ", font = ("Arial", 16), fg = "blue")
fahLabel.grid(row = 3, column = 1, pady = 10, sticky = NW)
celEntry = Entry (mainframe, width = 10, bd = 5, textvariable = celTempVar)
celEntry.grid(row = 2, column = 1, pady = 10, sticky = NW, padx = 125 )
fahEntry = Entry (mainframe, width = 10, bd = 5, textvariable = fahTempVar)
fahEntry.grid(row = 3, column = 1, pady = 10, sticky = NW, padx = 125 )
convertButton =Button (mainframe, text = "Convert", font = ("Arial", 8, "bold"), relief = RAISED, bd=5, justify = CENTER, highlightbackground = "red", overrelief = GROOVE, activebackground = "green", activeforeground="blue", command = convert)
convertButton.grid(row = 4, column = 1, ipady = 8, ipadx = 12, pady = 5, sticky = NW, padx = 55)
resetButton = Button (mainframe, text = "Reset", font = ("Arial", 8, "bold"), relief = RAISED, bd=5, justify = CENTER, highlightbackground = "red", overrelief = GROOVE, activebackground = "green", activeforeground="blue", command = reset)
resetButton.grid(row = 5, column = 1,ipady = 8, ipadx = 12, pady = 5, sticky = NW)
root.mainloop()
答案 0 :(得分:3)
问题在于这一行:
fahToCel = ((fahTemp - 32) * (5/9))
问题是5/9
是使用整数除法计算的(因为它的两个输入都是整数);它碰巧等于0
,这不是你想要的!有一大堆可能的修复,但最简单的方法就是使用明确处理浮点除法的5.0/9.0
。 (你也可以改变相反的方向,即使只是为了清晰。是的,它当前正在工作,但这是因为乘法 - 其中有celTemp
的浮点输入 - 在除法之前被处理。)