[英]How can I assign a value from OptionMenu (tkinter) to use it later?
我对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")
默认情况下,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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.