How to get the index of selected option in Tkinter Combobox?
In this article, we will be discussing how to get the index of the selected options in the Tkinter Combobox.
A Combobox is a combination of a Listbox and an Entry widget. This widget allows users to select one value from a set of values.
Syntax:
def get_index(*arg):
Label(app, text="The value at index " + str(combo.current()) +\
" is" + " " + str(var.get()), font=('#Font of Text')).pack()
var = StringVar()
combo = ttk.Combobox(app, textvariable=var)
var.trace('w', get_index)
Stepwise Implementation:
Step 1: First of all, import the library Tkinter.
from tkinter import *
from tkinter import ttk
Step 2: Now, create a GUI app using Tkinter.
app=Tk()
Step 3: Next, set the geometry of the app.
app.geometry("#Dimensions of the app")
Step 4: Further, create a function to clear the Combobox.
def clear():
combo.set('')
Step 5: Later on, create a function to set the index of the selected option in Combobox.
def get_index(*arg):
Label(app, text="The value at index " + str(combo.current())\
+ " is" + " " + str(var.get()), font=('#Font of Text')).pack()
Step 6: Moreover, create a tuple of some values to be added in the Combobox.
months = ('January', 'February', 'March', 'April', 'May',
'June', 'July','August','September','October',
'November','December')
Step 7: Then, create a Combobox widget and add the values in that Combobox.
var = StringVar()
combo = ttk.Combobox(app, textvariable=var)
combo['values'] = months
combo['state'] = 'readonly'
combo.pack(padx=#x-axis padding value, pady=#y-axis padding value)
Step 8: To a greater extent, set the tracing for the given variable.
var.trace('w', get_index)
Step 9: Furthermore, create a button to clear the selected Combobox text value.
button = Button(app, text="Clear", command=clear)
button.pack()
Step 10: Finally, make an infinite loop for displaying the app on the screen.
app.mainloop()
Example:
Python3
from tkinter import *
from tkinter import ttk
app = Tk()
app.geometry( "600x400" )
def clear():
combo. set ('')
def get_index( * arg):
Label(app, text = "The value at index " + str (combo.current()) +
" is" + " " + str (var.get()), font = ( 'Helvetica 12' )).pack()
months = ( 'January' , 'February' , 'March' , 'April' , 'May' , 'June' ,
'July' , 'August' , 'September' , 'October' , 'November' ,
'December' )
var = StringVar()
combo = ttk.Combobox(app, textvariable = var)
combo[ 'values' ] = months
combo[ 'state' ] = 'readonly'
combo.pack(padx = 5 , pady = 5 )
var.trace( 'w' , get_index)
button = Button(app, text = "Clear" , command = clear)
button.pack()
app.mainloop()
|
Output:
Last Updated :
22 Apr, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...