> Im working on a small tkinter app, in which I have a Toplevel widget
> containing an entry field and a listbox, and at the bottom, there's
> an "Ok" button.
>
> What I want is to have the user put their name in the entry box,
> click one of the items in the listbox, then click "Ok".
>
> My code looks like this:
>
> ...
> lb = Listbox(j)
> lb.config(selectmode=SINGLE, setgrid=1)
>
> def handleJoinClick(event, lb=lb):
> index = lb.curselection()
> label = lb.get(index)
> sys.stderr.write("selected %s %s\n"%(repr(index), repr(label)))
>
> lb.bind("<Button-1>", handleJoinClick)
> lb.pack()
> ...
>
> However, the -first- time I click -once-, the listbox claims that nothing's
> been selected:
>
> Exception in Tkinter callback
> Traceback (innermost last):
> File "/magnet/tools/users/davem/modules/Tkinter.py", line 551, in __call__
> return apply(self.func, args)
> File "GameFrame.py", line 106, in handleJoinClick
> label = lb.get(index)
> File "/magnet/tools/users/davem/modules/Tkinter.py", line 1223, in get
> return self.tk.call(self._w, 'get', first)
> TclError: bad listbox index "": must be active, anchor, end, @x,y, or a number
>
> But the -second- time I click -once- , it works fine:
>
> selected ('0',) 'Gathering (1): asdf'
>
>
> Can anyone shed some light on the situation for me pretty please?
You are mistaken wrt the correctness of the second click: the index you get
belongs to the item you clicked the *first* time.
Generally, when you bind a new function to a Tk event that has a default
function bind'ed to it, your function will be executed first and then the
standard one will be executed. (You can prevent the latter by letting
the first function return the string "break".)
In the present case, the selection is updated (Tk default function) *after*
handleJoinClick is called.
The solution to this problem is to process the event directly by using
the Listbox.nearest method.
Replacing the 'index = lb.curselection()' line with:
index = lb.nearest( event.y )
should do the trick.
cjr
--
Case Roole <c...@bound.xs4all.nl>