Tkinter ListBox selects specific index items
If the selection_set() method contains a parameter indicating the selection of this index item, this function is often used to set the initial selection of items after a Listbox has been created.
Tkinter ListBox selects specific index items Example#1
Create a Listbox, and set the initial selection to be the item with index 0.
from tkinter import *
fruits = [
"Banana","Watermelon","Pineapple",
"Orange","Grapes","Mango"
]
root = Tk()
root.title("apidemos.com")
root.geometry("300x210")
lb = Listbox(root)
for fruit in fruits:
lb.insert(END,fruit)
lb.pack(pady=10)
lb.selection_set(0) # Default selects the 0th item
root.mainloop()
Output:
If there are two arguments within the selection_set() method, it means the selection interval option, the first argument is the starting index item of the interval and the second argument is the ending index item of the interval.
Tkinter ListBox selects specific index items Example#2
Create a Listbox, and then set the initial selection items to be those with indexes 0 to 3.
from tkinter import *
fruits = [
"Banana","Watermelon","Pineapple",
"Orange","Grapes","Mango"
]
root = Tk()
root.title("apidemos.com")
root.geometry("300x210")
lb = Listbox(root,selectmode=EXTENDED) # Drag and drop can be multi-selected
for fruit in fruits: # Establishing fruit projects
lb.insert(END,fruit)
lb.pack(pady=10)
lb.selection_set(0,3) # Default selects items 0-3
root.mainloop()
Output: