Tkinter OptionMenu 显示选项和赋值 [英] Tkinter OptionMenu DisplayOptions and Assignment Values

查看:38
本文介绍了Tkinter OptionMenu 显示选项和赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 的 Tkinter OptionMenu 中,是否可以有一个显示选项列表,但在选择时,它会将一个值设置为其他值?

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?

假设我有

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

并希望显示值但将键分配给变量.这甚至可能吗?或者有没有办法链接OptionMenu来调用选择函数来转换它?

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?

我真正的问题比示例更复杂,所以问题只是评估复杂的字符串,我想避免使用 StringVar.

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.

谢谢

推荐答案

您已经拥有了.使用字典将您显示的选项映射到您想要的实际值.

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

请注意splat 运算符,*,用于将键解包为 OptionMenu 的逗号分隔参数列表.稍后当您想要选项的值"时,使用 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.

这篇关于Tkinter OptionMenu 显示选项和赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆