Default to and select the first item in Tkinter Listbox


Tkinter Listbox widgets are used to display a scrollable list of items with vertically stacked menus. Sometimes, we may need to set the list item selected, by default. We can use the select_set(list_item_index) method by specifying the index of the list items that need to be selected by default.

So, let us suppose that we have a list of programming languages in our Listbox and what we want is to set the first item selected, then we can provide the index of a first list item in the method. The method must be invoked before the end of mainloop() function.

Example

#Import tkinter library
from tkinter import *
#Create an instance of Tkinter frame or window
win= Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")
listbox=Listbox(win) #Create a listbox widget
listbox.pack(padx=10,pady=10,fill=BOTH, expand=True)
listbox.insert(1, "Python")
listbox.insert(2, "Java")
listbox.insert(3, "C++")
listbox.insert(4, "Rust")
listbox.insert(5, "GoLang")
listbox.insert(6, "C#")
listbox.insert(7, "JavaScript")
listbox.insert(8, "R")
listbox.insert(9, "Php")

#Select the first item of listbox
listbox.select_set(0)
win.mainloop()

Output

Running the above code will display a list of programming languages.

In the given output, the first list item in the list box is selected, by default.

Updated on: 03-May-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements