Get the index of a selected item in a ttk.Combobox
Question: Get the index of a selected item in a
ttk.Combobox
Core point: Use <seq>.index
to get the index of the selected item
Reference
Return zero-based index in the seq of the first item whose value is equal to x
The
.get()
method returns the current selected item of theCombobox
Bind the virtual event
<<ComboboxSelected>>
to the Combobox widget
import tkinter as tkimport tkinter.ttk as ttkclass App(tk.Tk): def __init__(self): super().__init__() self.combobox = combobox = ttk.Combobox(self) combobox['values'] = ("Speed, Distance, Time", "Speed, Acceleration, Time", "Gravitational Potential Energy(Ep)" ) combobox.pack() button = tk.Button(text="Submit", command=self.on_clicked) button.pack() def on_clicked(self, *event): selected = self.combobox.get() if selected: idx = self.combobox['values'].index(selected) print('simpleFormulaMenu({}), selected: {}'.format(idx, selected)) if idx in (2, 3, 4): # pass pass else: # simpleFormulaMenu(idx) passif __name__ == '__main__': App().mainloop()
Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6