如何从OptionMenu(tkinter)中分配值以便以后使用它?

时间:2017-07-24 04:42:35

标签: python user-interface tkinter

我是Python的新手,并尝试创建一个转换单位的程序(使用tkinter)。我想我在第5行遇到了问题。任何人都可以检查我的代码,并给我一些建议来解决它?谢谢

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 个答案:

答案 0 :(得分: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()