Tkinter OptionMenu DisplayOptions and Assignment Values
Asked Answered
S

1

8

In Python's Tkinter OptionMenu, is it possible to have a list of display options, but on selection, it sets a value to be some other value?

Suppose I had

variable = tk.IntVar(master)
OptionMenu(master, variable, 1, 2).pack()
options = {1:"one",2:"two"}

and wanted to display the values but assign the key to variable. Is this even possible? Or is there a way to link the OptionMenu to call a function on selection to convert it?

My real problem is more involved than the example, so the issue is just evaluating complex strings and I'd like to avoid using a StringVar.

Thanks

Subdelirium answered 20/12, 2014 at 6:39 Comment(0)
S
10

You already have it. Use the dictionary to map your displayed options to the actual values you want.

EG:

import Tkinter as tk
master = tk.Tk()
variable = tk.StringVar(master)
options = {"one": 1, "two": 2}
tk.OptionMenu(master, variable, *options.keys()).pack()
...
wanted = options[variable.get()]

Please note the splat operator, *, used to unpack the keys as a comma separated list of arguments to OptionMenu. Later when you want the option's "value" use variable.get() as the "key" in the dictionary.

Stanwinn answered 20/12, 2014 at 7:17 Comment(1)
I missed the ability for an option menu to link to a dictionary like that. This is great. Thanks.Subdelirium

© 2022 - 2024 — McMap. All rights reserved.