0

所以我正在制作一个温度转换器,但我无法将它用于华氏到摄氏度的计算。它可以从摄氏温度到华氏温度,但它不会以另一种方式转换。我不确定是什么问题导致了这个我已经尝试了 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()
4

1 回答 1

3

问题是这一行:

fahToCel = ((fahTemp - 32) * (5/9))

问题是5/9使用整数除法计算(因为它的两个输入都是整数);它恰好等于0,这不是您想要的!有很多可能的修复方法,但最简单的方法是使用5.0/9.0明确处理浮点除法的方法。(您也可以更改相反的方向,即使只是为了清楚起见。是的,它目前正在工作,但这是因为乘法(具有浮点输入)celTemp是在除法之前处理的。)

于 2012-06-14T22:52:38.953 回答