如何从选项菜单 (tkinter) 分配值以供以后使用?



我对Python完全陌生,并试图创建一个转换单位的程序(使用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")

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()

最新更新