pythonpython-3.xtkintertkinter.optionmenu

Tkinter bringing chosen option from optionMenu into a variable for further use


when creating a drop-down menu in "tkinter" like this:

options = ['0',
           '1',
           '2',
           '3',
           '4']

option = tk.OptionMenu(menu, var, *options)

var.set('Select number')

I want to know exactly how I can take the integer that the user has chosen and turn it into a variable that I can use later on.


Solution

  • Question: how I can take the integer that the user has chosen

    You define options as a list of str, therefore the chosen option are assigned to the given textvariable, in your code var. To get a integer from the str do:

    option_int = int(var.get())
    

    Working example, how to get the index of a chosen OptionMenu item:

    import tkinter as tk
    
    class myOptionMenu(tk.OptionMenu):
        def __init__(self, parent):
            self.item = tk.StringVar()
            self.item.set("Select option")  # default value
            self.index = None
            self.options = ['0. Option', '1. Option', '2. Option', '3. Option']
    
            super().__init__(parent, self.item, *self.options, command=self.command)
            self.pack()
    
        def command(self, v):
            # Loop 'options' to find the matching 'item', return the index
            self.index = [i for i, s in enumerate(self.options) if s == self.item.get()][0]
            print("def option({}), variable.get()=>{}, index:{}".format(v, self.item.get(), self.index))
            # >>> def option(2. Option), variable.get()=>2. Option, index:2
    
    root = tk.Tk()
    
    option = myOptionMenu(root)
    
    root.mainloop()
    

    Usage in the main loop:

    if option.item.get() == '2. Option':
        print("Option {} is selected.".format(option.item.get()))
    
    if option.index == 2:
        print("Option {} is selected.".format(option.index))
    

    Tested with Python:3.5.3 - TkVersion: 8.6