温度对话华氏温度到摄氏温度

时间:2016-07-29 22:26:46

标签: python python-2.7 tkinter

我正在尝试将温度从华氏温度转换为摄氏温度,反之亦然。 “>>>>”将华氏温度转换为摄氏温度时,摄氏温度按钮功能不起作用。请帮助,我想我已经看了太长时间的代码,这就是我无法弄明白的原因。

from Tkinter import *
   class Temp(Frame):
    def __init__(self):
        Frame.__init__(self)
 #               self._fahren = 0.0
 #               self._cel = 0.0
        self.master.title("TempConver")
        self.grid()
        self._fahrenLabel = Label(self, text="Fahrenheit")
        self._fahrenLabel.grid(row=0, column=0)
        self._fahrenVar = DoubleVar()
        self._fahrenVar.set(32.0)
        self._fahrenEntry = Entry(self, textvariable = self._fahrenVar)
        self._fahrenEntry.grid(row=1, column=0)
        self._celLabel = Label(self, text="Celcius")
        self._celLabel.grid(row=0, column=2)
        self._celVar = DoubleVar()
        self._celEntry = Entry(self, textvariable = self._celVar)
        self._celEntry.grid(row=1, column=2)
        self._fahrenButton = Button(self, text = ">>>>", command = self.FtoC)
        self._fahrenButton.grid(row = 0, column = 1)
        self._celButton = Button(self, text = "<<<<", command = self.CtoF)
        self._celButton.grid(row = 1, column = 1)
    def FtoC(self):
        fahren = self._fahrenVar.get()
        cel = (5/9) * (fahren - 32)
        self._celVar.set(cel) 
    def CtoF(self):
        cel = self._celVar.get()
        fahren = (9/5) * (cel + 32)
        self._fahrenVar.set(fahren)



def main():
    Temp().mainloop()

    main()

1 个答案:

答案 0 :(得分:3)

您的问题与Python 2中的分区工作方式有关。

比较

a=(5/9)
b=(5/9.0)

在第一种情况下,结果是整数。在第二种情况下,它是一个浮动。如果你除去两个整数,它将返回一个向下舍入的整数,在你的情况下为0,在任何情况下都会得到0的答案。如果两者中的任何一个是浮点数,则结果将是浮点数。在Python 3中,任何一种情况都会给出相同的浮点结果。

这应该有效:

def FtoC(self):
    fahren = self._fahrenVar.get()
    cel = (5/9.0) * (fahren - 32)
    self._celVar.set(cel) 

顺便说一句,您的摄氏温度到华氏温度的转换公式不正确。在添加32之前首先乘以9/5! 它应该是:

fahren = ((9/5.0) * cel) + 32
相关问题