2017-07-24 42 views
0

我對Python完全陌生並試圖創建一個程序(使用tkinter)來轉換單位。我想我在第五線有問題。任何人都可以檢查我的代碼,並給我一些建議來解決它?謝謝如何從OptionMenu(tkinter)中指定一個值以便稍後使用它?

choices = {'feet': 0.3048, 'inches': 0.0254} 
choice = StringVar() 
popupChoice = OptionMenu(secondFrame, choice, *choices) 
popupChoice.pack() 
pick_choice = choices[choice.get()] 

def calculate(*args): 
    try: 
     value = float(feet.get()) 
     meter.set(value*float(pick_choice)) 
    except ValueError: 
     print("error") 

回答

1

STRINGVAR()作爲默認爲您提供空字符串「」,所以沒有什麼可以在你的字典中達到並KeyError異常升高。簡單如果應該這樣做。

# choices.keys() will provide list of your keys in dictionary 
if choice.get() in choices.keys(): 
    pick_choice = choices[choice.get()] 

或者你可以之前設定的默認值,例如:

choice = StringVar() 
choice.set("feet") 

例如,如何能期待:

from tkinter import * 

def calculate(): 
    try: 
     value = float(feet.get()) 
     label.config(text=str(value*float(choices[choice.get()]))) 
    except ValueError or KeyError: 
     label.config(text='wrong/missing input') 
# config can change text and other in widgets 

secondFrame = Tk() 
# entry for value 
feet = StringVar() 
e = Entry(secondFrame, textvariable=feet) 
e.grid(row=0, column=0, padx=5) # grid is more useful for more customization 
# label showing result or other text 
label = Label(secondFrame, text=0) 
label.grid(row=0, column=2) 
# option menu 
choices = {'feet': 0.3048, 'inches': 0.0254} 
choice = StringVar() 
choice.set("feet") # default value, to use value: choice.get() 
popupChoice = OptionMenu(secondFrame, choice, *choices) 
popupChoice.grid(row=0, column=1, padx=5) 
# button to launch conversion, calculate is not called with variables 
# call them in function, or use lambda function - command=lambda: calculate(...) 
button1 = Button(secondFrame, command=calculate, text='convert') 
button1.grid(row=1, column=1) 
secondFrame.mainloop() 
+0

如果我的代碼繼續執行下面這段代碼,它會顯示「pick_choice」未定義: def calculate(* args): 嘗試: va略=浮動(feet.get()) meter.set(值*浮動(pick_choice)) 除了ValueError異常: 打印( 「錯誤」) –

+0

這是因爲Tkinter的是循環運行,你不想通話您的值立即,因爲他們不需要定義,如果你使用用戶輸入。最好是在你需要的時候定義它,所以在計算函數中。看到例子,我希望,這將解決所有問題。 – Foxpace

相關問題