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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…