Thach Nguyen
Thach Nguyen

Reputation: 5

How can I assign a value from OptionMenu (tkinter) to use it later?

I am totally new to Python and trying to create a program (using tkinter) that converts units. I think I have a problem in the 5th line. Can anyone examine my codes and give me some suggestion to fix it? Thank you

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

Upvotes: 0

Views: 827

Answers (1)

Foxpace
Foxpace

Reputation: 114

StringVar() as default provides you empty string ' ', so nothing can be reached in your dictionary and KeyError is raised. Simple If should do it.

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

Or you can set default value before it, for example:

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

Example, how it can look:

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

Upvotes: 1

Related Questions