有没有办法从“OptionMenu”获取特定值?选择?

发布于 2025-01-19 16:38:46 字数 1623 浏览 1 评论 0原文

我想使用TKINTER创建一个下拉菜单,显示一些这样的选项,但是我想要一些选择“一 -2”选项时,您会得到特定的值(例如:“ 2”),并将该值使用该值入口。这样的事情吗?提前致谢。

我在线找到了此代码 - 仅用于参考

import tkinter as tk
from tkinter import ttk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.geometry("320x80")
        self.title('Tkinter OptionMenu Widget')

        # initialize data
        self.languages = ('One - 2', 'Two - 1', 'Three - 4', 'Four - 3', 'Five - 6', 'Six - 5', 'Seven - 8', 'Eight - 7', 'Nine - 0', 'Zero - 9')

        # set up variable
        self.option_var = tk.StringVar(self)

        # create widget
        self.create_widgets()

    def create_widgets(self):
        # padding for widgets using the grid layout
        paddings = {'padx': 5, 'pady': 5}

        # label
        label = ttk.Label(self, text='Select your most favorite number:')
        label.grid(column=0, row=0, sticky=tk.W, **paddings)

        # option menu
        option_menu = ttk.OptionMenu(
            self,
            self.option_var,
            self.languages[0],
            *self.languages,
            command=self.option_changed)
        
        option_menu.grid(column=1, row=0, sticky=tk.W, **paddings)

        # output label
        self.output_label = ttk.Label(self, foreground='red')
        self.output_label.grid(column=0, row=1, sticky=tk.W, **paddings)

    def option_changed(self, *args):
        self.output_label['text'] = f'You selected: {self.option_var.get()}'

if __name__ == "__main__":
    app = App()
    app.mainloop()

代码,来自“ https://www.pythontutorial.net/tkinter/tkinter/tkinter-optionmenu/”

I want to use tkinter to create a dropdown menu that shows some options like this, but i want something that when you select the option "One - 2" you get a specific value (e.g.: "2") and use that value for a entry. Is something like this possible? Thanks in advance.

I found this code online - just for reference

import tkinter as tk
from tkinter import ttk

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.geometry("320x80")
        self.title('Tkinter OptionMenu Widget')

        # initialize data
        self.languages = ('One - 2', 'Two - 1', 'Three - 4', 'Four - 3', 'Five - 6', 'Six - 5', 'Seven - 8', 'Eight - 7', 'Nine - 0', 'Zero - 9')

        # set up variable
        self.option_var = tk.StringVar(self)

        # create widget
        self.create_widgets()

    def create_widgets(self):
        # padding for widgets using the grid layout
        paddings = {'padx': 5, 'pady': 5}

        # label
        label = ttk.Label(self, text='Select your most favorite number:')
        label.grid(column=0, row=0, sticky=tk.W, **paddings)

        # option menu
        option_menu = ttk.OptionMenu(
            self,
            self.option_var,
            self.languages[0],
            *self.languages,
            command=self.option_changed)
        
        option_menu.grid(column=1, row=0, sticky=tk.W, **paddings)

        # output label
        self.output_label = ttk.Label(self, foreground='red')
        self.output_label.grid(column=0, row=1, sticky=tk.W, **paddings)

    def option_changed(self, *args):
        self.output_label['text'] = f'You selected: {self.option_var.get()}'

if __name__ == "__main__":
    app = App()
    app.mainloop()

code from "https://www.pythontutorial.net/tkinter/tkinter-optionmenu/"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪化雨蝶 2025-01-26 16:38:46

您可以将选项列表的内容更改为字典,例如 self.languages 变为:

# initialize data
self.options = {
    'One': 1,
    'Two': 2,
    'Three': 3,
    'Four': 4,
    'Five': 5,
    'Six': 6,
}

现在字典的键可以用作您的 OptionMenu 值

# option menu
option_menu = ttk.OptionMenu(
    self,
    self.option_var,
    *self.options.keys(),  # use dict keys as option items
    command=self.option_changed
)

要从字典中获取值,只需更新option_changed() 如下:

def option_changed(self, *args):
    # get the selected option string
    selected = self.option_var.get()
    # get the value from the options dictionary
    self.output_label['text'] = f'You selected: {self.options[selected]}'

selected 将是与 self.options 字典中的键匹配的字符串,因此您可以使用该值来访问字典。还值得指出的是,字典中的值不一定是数字,它们可以是任何类型,甚至不必全部是同一类型!

FWIW,“选项”字典的键可以是数字或字符串,但为此目的处理字符串更容易(记住:这些是将填充菜单的字符串)。

快速编辑:我觉得我应该指出,无论如何,用于字典键的数据类型都会被 option_var“字符串化”,因为它是 tk.StringVar() -请注意!

You could change the contents of your option list to a dictionary, e.g. self.languages becomes:

# initialize data
self.options = {
    'One': 1,
    'Two': 2,
    'Three': 3,
    'Four': 4,
    'Five': 5,
    'Six': 6,
}

And now the keys of the dictionary can be used as your OptionMenu values

# option menu
option_menu = ttk.OptionMenu(
    self,
    self.option_var,
    *self.options.keys(),  # use dict keys as option items
    command=self.option_changed
)

To get the value from the dictionary, just update option_changed() as follows:

def option_changed(self, *args):
    # get the selected option string
    selected = self.option_var.get()
    # get the value from the options dictionary
    self.output_label['text'] = f'You selected: {self.options[selected]}'

selected will be a string matching a key in the self.options dict, so you can use that value to access the dictionary. It's also worth pointing out that the values in the dictionary don't have to be numbers, they can be any type, and they don't even all have to be the same type!

FWIW, the keys of the 'options' dict can be either numbers or strings, but strings are easier to deal with for this purpose (remember: these are the strings that will populate your menu).

Quick Edit: I feel like I should point out that the data type used for your dictionary keys gets "stringified" by option_var anyway, since it's a tk.StringVar() - just a heads up!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文