0

GUI、つまりTkinterモジュールを使用して、最初のメインプロジェクトの温度コンバーターを作成しています。GUI の初期化に問題はありません。それはうまくいきます(私の知る限り)。変換に関連する各関数を呼び出すための IF ステートメントを作成する際に支援が必要です。私が抱えている問題は、2 つの異なるリストからの 2 つのアイテム間の同等性を示す方法がわからないことです。これが私のコードです(いくつか不足していることはわかっています。明らかに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

ご覧いただき、ありがとうございます。知識は無駄になりません!乾杯

4

2 に答える 2

1

コメントで指摘されているように、いくつかのアーキテクチャの欠陥があり (学習中なのでこれは正常です)、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 fromUnit.get() == 'Celsius':
    if toUnit.get()) == 'Celsius':
        celsius_to_celsius()
    if toUnit.get()) == 'Fahrenheit':
        celsius_to_fahrenheit()
    if toUnit.get()) == 'Kelvin':
        celsius_to_kelvin()

3) 辞書 (連想配列) を使用して関数を格納する

converters = {
    'Celsius' : {
        'Celsius' : celsius_to_celsius,
        'Fahrenheit': celsius_to_fahrenheit,
        'Kelvin': celsius_to_kelvin},
    'Fahrenheit' : {
        'Celsius' : fahrenheit_to_celsius,
        'Fahrenheit': fahrenheit_to_fahrenheit,
        'Kelvin': fahrenheit_to_kelvin},
    #...
}
#retrieve function, and call it (through the () at the end)
converters [fromUnit.get()] [toUnit.get()] ()

実際、ネストされた辞書を使用しています。辞書を 1 つだけ使用することもできます

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またはfromUnit(それぞれ*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)


1 Tkinter 変数はオブジェクトであり、値と関連するメソッドを埋め込んだ複合アーティファクトです。は、通常の変数と同じ目的を果たしますがtraced、値が変更されたことを警告することができます。これらは、操作を容易にするために tkinter ウィジェットと組み合わせて使用​​されます。fromUnitここでは、 の内容をリテラル string と比較したいので、メソッドを介して文字列'Celsius'を問い合わせる必要があります。詳細については、http://effbot.org/tkinterbook/variable.htmを参照してください。fromUnitget

于 2012-10-17T14:03:39.830 に答える
0

これが私が上で始めたプログラムからの私の最終的なソースコードです。

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
于 2012-10-18T01:37:26.563 に答える