温度转换器问题

2024-09-29 23:32:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的第一个主要项目制作一个使用图形用户界面(GUI)的温度转换器,即Tkinter模块。初始化GUI没有任何问题。那(据我所知)效果很好。我需要一些帮助,使IF语句调用与转换相关的每个函数。我遇到的问题是,我不知道如何显示两个不同列表中的两个项目之间的等价性。这是我的代码(我知道我遗漏了一些东西。显然是if语句。)

from tkinter import *

gui = Tk()
gui.title(string='Temperature Converter')
#create the GUI
fromUnit = StringVar()
#variable which holds the value of which unit is active in "units1"
toUnit = StringVar()
#variable which holds the value of which unit is active in "units2"
initialTemp = StringVar()
#the initial temperature entered in "enterTemp" entry
initialTemp.set('0')
#set the initial temperature to 0
convertedTemp = StringVar()
#used to display the converted temperature through "displayTemp" 
convertedTemp.set('0')
#set the converted temperature to 0

units1 = ('Celsius', 'Fahrenheit', 'Kelvin') #the units used in the OptionMenu
units2 = ('Celsius', 'Fahrenheit', 'Kelvin')

fromUnit.set(units1[0]) #set the active element to the item in index[0] of units1
toUnit.set(units2[0]) #set the active element to the item in index[0] of units2

# celsius-celcius conversion
def celsius_to_celsius():
    currentTemp = float(initialTemp.get())
    convertedTemp.set(currentTemp)

# celsius-kelvin conversion
def celsius_to_kelvin():
    currentTemp = float(initialTemp.get())
    currentTemp = (currentTemp + 273.15)
    convertedTemp.set(currentTemp)

# celsius-fahrenheit conversion
def celsius_to_fahrenheit():
    currentTemp = float(initialTemp.get())
    currentTemp = (currentTemp * (9/5))+32
    convertedTemp.set(currentTemp)

#fahrenheit-fahrenheit conversion
def fahrenheit_to_fahrenheit():
    currentTemp = float(initialTemp.get())
    convertedTemp.set(currentTemp)

#fahrenheit-celsius conversion
def fahrenheit_to_celsius():
    currentTemp = float(initialTemp.get())
    currentTemp = ((currentTemp - 32)*(5/9))
    convertedTemp.set(currentTemp)

#fahrenheit-kelvin conversion
def fahrenheit_to_kelvin():
    currentTemp = float(initialTemp.get())
    currentTemp = ((currentTemp - 32)*(5/9)+273.15)
    convertedTemp.set(currentTemp)

#kelvin-kelvin conversion
def kelvin_to_kelvin():
    currentTemp = float(initialTemp.get())
    convertedTemp.set(currentTemp)

#kelvin-celsius conversion
def kelvin_to_celsius():
    currentTemp = float(initialTemp.get())
    currentTemp = (currentTemp - 273.15)
    convertedTemp.set(currentTemp)

#kelvin-fahrenheit conversion
def kelvin_to_fahrenheit():
    currentTemp = float(initialTemp.get())
    currentTemp = (((currentTemp - 273.15)*(9/5))+32)
    convertedTemp.set(currentTemp)

#main function
#contains the if statements which select which conversion to use
def convert_Temp():
    currentTemp = float(initialTemp.get())
    if (fromUnit, toUnit) == ('Celsius','Celsius'):
        celsius_to_celsius()


gui.geometry('+100+100')
#set up the geometry

enterTemp = Entry(gui,textvariable=initialTemp,justify=RIGHT)
enterTemp.grid(row=0,column=0)
#Entry which receives the temperature to convert

convertFromUnit = OptionMenu(gui,fromUnit,*units1)
convertFromUnit.grid(row=0,column=1)
#Option Menu which selects which unit to convert from

displayTemp = Label(gui,textvariable=convertedTemp)
displayTemp.grid(row=1,column=0)
#Label which displays the temperature
#Takes text variable "convertTemp"

convertToUnit = OptionMenu(gui,toUnit,*units2)
convertToUnit.grid(row=1,column=1)
#Option Menu which selects which unit to convert to

convertButton = Button(gui,text='Convert',command=convert_Temp)
convertButton.grid(row=2,column=1)
#Button that starts the conversion
#Calls the main function "convert_Temp"

gui.mainloop()
#End of the main loop

感谢您的观看以及您提供的任何帮助和批评。没有知识是浪费的! 干杯


Tags: thetowhichgetdefguifloatfahrenheit
2条回答

这是我从上面开始的程序的最终源代码。在

from tkinter import *

gui = Tk()
gui.title(string='Temperature Converter')
#create the GUI
fromUnit = StringVar()
#variable which holds the value of which unit is active in "units1"
toUnit = StringVar()
#variable which holds the value of which unit is active in "units2"
initialTemp = StringVar()
#set the initial temperature to 0
convertedTemp = StringVar()
#used to display the converted temperature through "displayTemp" 
convertedTemp.set('0')
#set the converted temperature to 0

units1 = ('Celsius', 'Fahrenheit', 'Kelvin') #the units used in the OptionMenu
units2 = ('Celsius', 'Fahrenheit', 'Kelvin')

fromUnit.set(units1[0]) #set the active element to the item in index[0] of units1
toUnit.set(units2[0]) #set the active element to the item in index[0] of units2

#main function
#contains the if statements which select which conversion to use
def convert_Temp():
    currentTemp = float(initialTemp.get())
    cu1 = fromUnit.get()
    cu2 = toUnit.get()

    if (cu1, cu2) == ('Celsius', 'Celsius'):
        c_c()
    elif (cu1, cu2) == ('Celsius', 'Kelvin'):
        c_k()
    elif (cu1, cu2) == ('Celsius', 'Fahrenheit'):
        c_f()
    elif (cu1, cu2) == ('Fahrenheit', 'Fahrenheit'):
        f_f()
    elif (cu1, cu2) == ('Fahrenheit', 'Celsius'):
        f_c()
    elif (cu1, cu2) == ('Fahrenheit', 'Kelvin'):
        f_k()
    elif (cu1, cu2) == ('Kelvin', 'Kelvin'):
        k_k()
    elif (cu1, cu2) == ('Kelvin', 'Celsius'):
        k_c()
    elif (cu1, cu2) == ('Kelvin', 'Fahrenheit'):
        k_f()
    else:
        messagebox.showerror(title='ERROR', message='Error in the IF statements')

# celsius-celcius conversion
def c_c():
    currentTemp = float(initialTemp.get())
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

# celsius-kelvin conversion
def c_k():
    currentTemp = float(initialTemp.get())
    currentTemp = (currentTemp + 273.15)
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

# celsius-fahrenheit conversion
def c_f():
    currentTemp = float(initialTemp.get())
    currentTemp = (currentTemp * (9/5))+32
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

#fahrenheit-fahrenheit conversion
def f_f():
    currentTemp = float(initialTemp.get())
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

#fahrenheit-celsius conversion
def f_c():
    currentTemp = float(initialTemp.get())
    currentTemp = (currentTemp - 32)*(5/9)
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

#fahrenheit-kelvin conversion
def f_k():
    currentTemp = float(initialTemp.get())
    currentTemp = ((currentTemp - 32)*(5/9)+273.15)
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

#kelvin-kelvin conversion
def k_k():
    currentTemp = float(initialTemp.get())
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

#kelvin-celsius conversion
def k_c():
    currentTemp = float(initialTemp.get())
    currentTemp = (currentTemp - 273.15)
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)

#kelvin-fahrenheit conversion
def k_f():
    currentTemp = float(initialTemp.get())
    currentTemp = (((currentTemp - 273.15)*(9/5))+32)
    currentTemp = round(currentTemp, 2)
    convertedTemp.set(currentTemp)


gui.geometry('+100+100')
#set up the geometry

enterTemp = Entry(gui,textvariable=initialTemp,justify=RIGHT)
enterTemp.grid(row=0,column=0)
#Entry which receives the temperature to convert

convertFromUnit = OptionMenu(gui,fromUnit,*units1)
convertFromUnit.grid(row=0,column=1)
#Option Menu which selects which unit to convert from

displayTemp = Label(gui,textvariable=convertedTemp)
displayTemp.grid(row=1,column=0)
#Label which displays the temperature
#Takes text variable "convertTemp"

convertToUnit = OptionMenu(gui,toUnit,*units2)
convertToUnit.grid(row=1,column=1)
#Option Menu which selects which unit to convert to

convertButton = Button(gui,text='Convert',command=convert_Temp)
convertButton.grid(row=2,column=1)
#Button that starts the conversion
#Calls the main function "convert_Temp"

gui.mainloop()
#End of the main loop

正如评论中指出的,您有一些架构缺陷(这是正常的,因为您正在学习),您可能会从CodeReview社区(它是stackexchange网络的另一个站点)得到有趣的反馈。

这里有几个选项可以用来执行您所称的If语句。事实上你 已经将转换包装在函数中拓宽了可能性。在

1)在if中列举所有组合

您已经开始了,但有一个区别:使用fromUnit.get()来访问tkinter变量的值1。在

if (fromUnit.get(), toUnit.get()) == ('Celsius','Celsius'):
    celsius_to_celsius()
if (fromUnit.get(), toUnit.get()) == ('Celsius','Fahrenheit'):
    celsius_to_fahrenheit()
if (fromUnit.get(), toUnit.get()) == ('Celsius','Kelvin'):
    celsius_to_kelvin()

2)嵌套if

^{pr2}$

3)使用字典(关联数组)存储函数

^{3}$

实际上,它使用嵌套字典。你也只能用一本字典

converters = {
    ('Celsius', 'Celsius') : celsius_to_celsius,
    ('Celsius', 'Fahrenheit'): celsius_to_fahrenheit,
    ('Celsius', 'Kelvin'): celsius_to_kelvin,
}
converters [(fromUnit.get(), toUnit.get())] ()

4)您使用的一致命名方案允许生成函数名

function_name = fromUnit.get().lower() + "_to_" + toUnit.get().lower()
globals()[function_name] ()

5)委托调度

通常,大组合if(或者存在的语言中的开关)是重构的一个吸引力。 例如,您可以对convertFromUnit或{}(分别是*toUnit)执行初步工作。在

使用嵌套字典的机制与Python对象中使用的机制非常接近。在

def fromUnitCallback():
    global _converter
    _converter = globals()[fromUnit.get()]()

def toUnitCallback():
    global _function_name
    _function_name = toUnit.get().lower()

def convert_Temp():
    currentTemp = float(initialTemp.get())
    _converter.set(currentTemp)
    converted = getattr(_converter, _function_name) ()
    convertedTemp.set(converted)

class Kelvin:
    def __init__(self, val=0):
        self.__kelvin = val

    def kelvin(self):
        return self.__kelvin

    def celsius(self):
        return self.__kelvin - 273.15

    def fahrenheit(self):
        return (self.__kelvin - 273.15)*1.8 + 32

    def set(self, val):
        self.__kelvin = val

class Celsius(Kelvin):
    def __init__(self, val):
        Kelvin.__init__(self)
        self.set(val)

    def set(self, val):
        Kelvin.set(self, val + 273.15)

class Fahrenheit:
    def __init__(self, val):
        Kelvin.__init__(self)
        self.set(val)

    def set(self, val):
        Kelvin.set((val - 32)*5/9 + 273.15)


1Tkinter变量是对象,即复合人工制品的嵌入值及其相关方法。除了它们可以是traced,也就是警告它们的值发生了变化。它们与tkinter小部件结合使用,以简化操作。在这里,您要将fromUnit的内容与文本字符串'Celsius'进行比较,因此您必须通过get方法询问fromUnit字符串。有关详细信息,请参见http://effbot.org/tkinterbook/variable.htm

相关问题 更多 >

    热门问题