Search code examples
pythontkinterlistbox

How to select only one item from Listbox?


I have a Listbox widget with multiple entries. I am using the method select_set(index) to select items from list but the problem is it is selecting more than one item without deselecting the previous one. I want to select only one item at a time. Since selectmode is 'single' so shouldn't it select only one item? I tried selection_set(1,1) but it also doesn't seem to work.

How can I deselect all other entries and select only one entry?

import tkinter as tk

root = tk.Tk()

group_list = tk.Listbox(root, height=10, selectmode='single')
group_list.pack()

group_list.insert(0, "Group 1")
group_list.insert(1, "Group 2") #selects group 2 as well without deselecting group 1

group_list.select_set(0)
group_list.select_set(1)

root.mainloop()

Solution

  • You can clear a selection by using the method group_list.select_clear()

    Edit:

    To clarify:

    • To remove a single selection: .select_clear(index)
    • To remove all selections use: .select_clear(0, tk.END)