简体   繁体   中英

Is there a way to get a specific value from a 'OptionMenu' selection?

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 (eg: "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/"

You could change the contents of your option list to a dictionary, eg 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM