1

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.

stovfl
  • 14,998
  • 7
  • 24
  • 51
Coder Cody
  • 95
  • 1
  • 10
  • 2
    Your question can be answered just by reading available documentation. What part of the problem are you struggling with? It looks like you already know how to associate the widget with a variable. – Bryan Oakley Oct 17 '18 at 20:18

1 Answers1

3

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

stovfl
  • 14,998
  • 7
  • 24
  • 51