Andrew Lalis
Andrew Lalis

Reputation: 974

Tkinter Listbox How to tell if an item is selected

I am trying to create a simple GUI that allows the user to press a button, which will delete an entry from a shown Listbox. However, the console throws an error if no entry is selected, so how would I determine if the user has selected an entry. Here's my code:

selection = self.recipe_list.curselection()
    if not selection is None:
        self.recipe_list.delete(selection)
    else:
        print("Nothing to delete!")

Upvotes: 2

Views: 8595

Answers (4)

Wickie
Wickie

Reputation: 1

I know this was answered a while ago but I thought I would add my two cents:

I've found that because technically the listbox can have multiple selected values that I can use this:

for item in self.my_listbox.curselection()[::-1]:
   my_listbox.delete(item)

It doesn't allow the opportunity to present a message box to the user if there is no item but it will delete ALL selected items and won't complain if there are none

Upvotes: 0

1966bc
1966bc

Reputation: 1308

According with

Tkinter reference: a GUI for Python

Methods on listbox objects include:

.curselection()

Returns a tuple containing the line numbers of the selected element or elements, counting from 0.

If nothing is selected, returns an empty tuple.

So you can do somenthing like this

if self.MyListbox.curselection():
        index = self.MyListbox.curselection()[0]

Upvotes: 3

PythonProgrammi
PythonProgrammi

Reputation: 23443

if not self.lstb.curselection() is ():

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49320

Instead of returning None like you're checking for, it returns an empty string, "". Check for that as follows:

if selection:
    self.recipe_list.delete(selection)
else:
    print("Nothing to delete!")

Upvotes: 3

Related Questions