Home > Software design >  select_set() method of Listbox tkinter widget in Python enables multiple selections even selectionmo
select_set() method of Listbox tkinter widget in Python enables multiple selections even selectionmo

Time:11-17

I am working with Python 3.10.5 64bit and a strange behavior regarding the listboy widget of the tkinter modul.

Look at the following code:

import tkinter as tk

root = tk.Tk()

cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']
list_source = tk.StringVar(value=cities)

lst_cities = tk.Listbox(
    master=root,
    listvariable=list_source,
    height=6,
    selectmode=tk.SINGLE,
    exportselection=False) # enables that the selected item will be highlighted

lst_cities.grid(row=0, column=0, sticky=tk.EW)

lst_cities.select_set(0)
lst_cities.select_set(1)
lst_cities.select_set(2)

root.mainloop()

As you can see I have created a simple listbox and finally used the 'select_set' method several times with different indexes. I would assume as I have set selectmode to SINGLE that a new 'select_set' call would remove the previous selection, but this isn't the case so I ended with 3 selected entries. Is this a desired behavior? If so it looks like an inconsistent behavior.

I tried to clear the selection with: ` lst_cities.selection_clear(tk.END) lst_cities.select_clear(tk.END)

but this doesn't seem to have any effect. So I am also looking for way to clear the selection, so I can select a new entry. Seems I am missing something.

CodePudding user response:

According to the help on selection_set():

selection_set(self, first, last=None)
    Set the selection from FIRST to LAST (included) without
    changing the currently selected elements.

currently selected elements are not affected.

So you need to clear current selections using selection_clear() (or select_clear()):

selection_clear(0, "end")

Better to use a function to simplify it:

def select_set(idx):
    lst_cities.selection_clear(0, "end")
    lst_cities.selection_set(idx)

selection_set(0)
selection_set(1)
selection_set(2)

CodePudding user response:

The simple way to do this. As you saying that several times with different indexes by using tk.MULTIPLE is good choice instead of tk.SINGLE. There are several ways to do.

import tkinter as tk

root = tk.Tk()
root.geometry("200x200")

cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']

def remove_item():
    selected_checkboxs = lst_cities.curselection()

    for selected_checkbox in selected_checkboxs[::-1]:
        lst_cities.delete(selected_checkbox)

lst_cities = tk.Listbox(root,
                        selectmode=tk.MULTIPLE,
                        exportselection=False,
                        height=6)
lst_cities.pack()

for item in cities:
    lst_cities.insert(tk.END, item)

tk.Button(root, text="delete", command=remove_item).pack()

root.mainloop()

Result MULTIPLE:

enter image description here

Result after delete:

enter image description here

  • Related