Tk Listbox - Selected Item ?
Peter Moscatt
pgmoscatt at optushome.com.au
Fri Apr 15 05:29:09 EDT 2005
Martin Franklin wrote:
> Peter Moscatt wrote:
>> 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.
>>
>
> Pete,
>
> Sounds like you are using the wrong kind of bind event. That is the
> first time you select an item the callback for the bind command is
> called *before* the selection is made. Can you post the code you have
> showing the bind method and callback?
>
> This code shows three different bind methods, the first produces the
> same exception that you got...
>
>
> from Tkinter import *
>
>
> root = Tk()
> lb = Listbox(root)
> lb.insert(0, "one")
> lb.insert(0, "two")
> lb.insert(0, "three")
> lb.pack()
>
> def callback(*event):
> print lb.get(lb.curselection()[0])
>
> ## BAD
> #~ lb.bind("<1>", callback)
>
> ## OK
> #~ lb.bind("<ButtonRelease-1>", callback)
>
> ## Best
> lb.bind("<<ListboxSelect>>", callback)
>
> root.mainloop()
>
>
> The <<ListboxSelect>> is a virtual event I think quick google would tell
> you more and the Tk man pages (online) have a complete explanation...
>
> http://www.tcl.tk/man/tcl8.4/TkCmd/listbox.htm
> http://www.tcl.tk/man/tcl8.4/TkCmd/listbox.htm#M60
>
>
> Cheers,
> Martin.
Thanks Martin,
You're a legend !!!!!
I fixed the bind and used lb.bind("<<ListboxSelect>>", callback) and away it
went.
Thanks heaps for the help.
Pete
More information about the Python-list
mailing list