Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter listbox change highlighted item programmatically

Tags:

python

tkinter

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?

like image 764
user2018473 Avatar asked Nov 26 '14 20:11

user2018473


2 Answers

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.

like image 142
abarnert Avatar answered Sep 18 '22 02:09

abarnert


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)}')
like image 38
ilya Avatar answered Sep 19 '22 02:09

ilya