user2018473
user2018473

Reputation: 245

Tkinter listbox change highlighted item programmatically

I have a listbox in Tkinter and I would like to change the item selected programatically when the user presses a key button. I have the keyPressed method but how do I change the selection in the Listbox in my key pressed method?

Upvotes: 10

Views: 14494

Answers (2)

ilya
ilya

Reputation: 101

If you need ListboxSelect event to be also triggered, use below code:

# create
self.lst = tk.Listbox(container)
# place
self.lst.pack()
# set event handler
self.lst_emails.bind('<<ListboxSelect>>', self.on_lst_select)

# select first item
self.lst.selection_set(0)
# trigger event manually
self.on_lst_select()

# event handler
def on_lst_select(self, e = None):
   # Note here that Tkinter passes an event object to handler
   if len(self.lst.curselection()) == 0:
       return
   index = int(self.lst.curselection()[0])
   value = self.lst.get(index)
   print (f'new item selected: {(index, value)}')

Upvotes: 2

abarnert
abarnert

Reputation: 365717

Because listboxes allow for single vs. continuous vs. distinct selection, and also allow for an active element, this question is ambiguous. The docs explain all the different things you can do.

The selection_set method adds an item to the current selection. This may or may not unselect other items, depending on your selection mode.

If you want to guarantee that you always get just that one item selected no matter what, you can clear the selection with selection_clear(0, END), then selection_set that one item.

If you want to also make the selected item active, also call activate on the item after setting it.

To understand about different selection modes, and how active and selected interact, read the docs.

Upvotes: 12

Related Questions