Tk Listbox - Selected Item ?

Peter Moscatt pgmoscatt at optushome.com.au
Fri Apr 15 03:53:49 EDT 2005


Martin Franklin wrote:

> Peter Moscatt wrote:
>> I am having trouble understanding the methods for the Listbox from Tk.
>> 
>> If I was to select at item in the list using a mouse click (have already
>> created the bind event) - what method returns the text of the selected
>> item ?
>> 
>> Pete
>> 
> 
> 
> Pete,
> 
> pydoc Tkinter.Listbox
> 
> <snip>
> 
>   |  curselection(self)
>   |      Return list of indices of currently selected item.
>   |
>   |  delete(self, first, last=None)
>   |      Delete items from FIRST to LAST (not included).
>   |
>   |  get(self, first, last=None)
>   |      Get list of items from FIRST to LAST (not included).
> 
> So to get the value of the selected item:
> 
> lb.get(lb.curselection()[0])
> 
> 
> provided the listbox is in single selection mode or only one item is
> selected
> 
> Martin

Thanks Martin,

I used the:
  lb.get(lb.curselection()[0])

ant this works to a point.  When I select the item in the listbox the system
generates an error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.3/lib-tk/Tkinter.py", line 1345, in __call__
    return self.func(*args)
  File "/home/linux/programming/dxcluster/servers.py", line 37, in sel
    items = self.listbox.get(self.listbox.curselection()[0])
IndexError: tuple index out of range


Then if I select a second time directly after the error message I get my
desired result.

Am I to you the code you quoted in your original message:

>   |  curselection(self)
>   |      Return list of indices of currently selected item.
>   |
>   |  delete(self, first, last=None)
>   |      Delete items from FIRST to LAST (not included).
>   |
>   |  get(self, first, last=None)
>   |      Get list of items from FIRST to LAST (not included).



Pete






More information about the Python-list mailing list