Вопрос : как я могу получить целое число, которое выбрал пользователь
Вы определяете options
как список str
, следовательно, выбранныйОпция присваивается данному textvariable
, в вашем коде var
.Чтобы получить integer
из str
do:
option_int = int(var.get())
Рабочий пример, как получить index
выбранного OptionMenu
элемента:
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()
** Использование в основном цикле:
if option.item == '2. Option':
print("Option {} is selected.".format(option.item))
if option.index == 2:
print("Option {} is selected.".format(option.index))
Протестировано с Python: 3,5,3 - TkVersion: 8,6