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?
-
Your second question is a separate question, and should be asked as such. Also, unless you provide code (a [minimal, complete, verifiable example](http://stackoverflow.com/help/mcve), not a dump of your whole program), you're relying on someone guessing at what you might be doing wrong, which lowers your chances of getting a useful answer. – abarnert Nov 26 '14 at 21:00
-
I think the answer in the following link may have been what you were looking for https://stackoverflow.com/a/25451279/996205 – Thom Ives Sep 22 '20 at 20:10
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.

- 354,177
- 51
- 601
- 671
-
4Any ideas on an alternative tkinter docs site to effbot.org or know if/when it might be coming back online? – drevicko Apr 05 '22 at 01:36
-
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)}')

- 101
- 1
- 2
- 4