How to get the index of selected option in Tkinter Combobox?

TkinterPythonGUI-Programming

If you want to create a dropdown list of items and enable the items of list to be selected by the user, then you can use the Combobox widget. The Combobox widget allows you to create a dropdown list in which the list of items can be selected instantly. However, if you want to get the index of selected items in the combobox widget, then you can use the get() method. The get() method returns an integer of the selected item known as the index of the item.

Example

Let’s take an example to see how it works. In this example, we have created a list of days of weeks in a dropdown list and whenever the user selects a day from the dropdown list, it will print and display the index of selected item on a Label widget. To print the index, we can concatenate the string by typecasting the given index into string.

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Create a function to clear the combobox
def clear_cb():
   cb.set('')
   
# Define Days Tuple
days= ('Sun','Mon','Tue','Wed','Thu','Fri','Sat')

# Function to print the index of selected option in Combobox
def callback(*arg):
   Label(win, text= "The value at index " + str(cb.current()) + " is" + " "+ str(var.get()), font= ('Helvetica 12')).pack()
   
# Create a combobox widget
var= StringVar()
cb= ttk.Combobox(win, textvariable= var)
cb['values']= days
cb['state']= 'readonly'
cb.pack(fill='x',padx= 5, pady=5)

# Set the tracing for the given variable
var.trace('w', callback)

# Create a button to clear the selected combobox text value
button= Button(win, text= "Clear", command= clear_cb)
button.pack()

win.mainloop()

Output

Running the above code will display a combobox widget with a list of days. Whenever you select a day from the list, it will print the index and the corresponding item on the label widget.

raja
Updated on 16-Dec-2021 11:15:20

Advertisements