[Tkinter-discuss] Can't do proper event binding in a for loop
michael.odonnell at uam.es
Tue Oct 19 21:43:57 CEST 2010
Much simpler, and closer to the original posters intention.
Replace your up_and_down function with:
for i in range(len(buttons)-1):
buttons[i].bind("<Down>", lambda e, x=buttons[i+1]: x.focus_set())
for i in range(1, len(buttons)):
buttons[i].bind("<Up>", lambda e, x=buttons[i-1]: x.focus_set())
...basically, with this code, the "i" is being evaluated within the loop,
and passed to the lambda as the x parameter. The 'e' parameter
will be set to the event object.
On Tue, Oct 19, 2010 at 2:01 PM, thea_t <siatogia at yahoo.com> wrote:
> Thank you guys! I know what's wrong now! :)
> Michael Lange wrote:
>> Thus spoketh Firat Ozgul <ozgulfirat at gmail.com>
>> unto us on Tue, 19 Oct 2010 13:19:03 +0300:
>>> for loop doesn't work, because in a for loop all events will be bound
>>> all at once, and you will only see the effect of the last binding. You
>>> need something that binds events one by one.
>>> If I were you, I would use the next() method of Python iterators:
>> I think the OP suffered from a different problem in her code, namely the
>> IndexError that will be raised when i+1 or i-1 become >2 or <0 .
>> I guess what she wanted to achieve can be done, but not with this simple
>> lambda, she needs to catch the IndexError with something like:
>> def up_and_down(*buttons):
>> def callback(event):
>> index = list(buttons).index(event.widget)
>> if event.keysym == 'Up':
>> buttons[index - 1].focus_set()
>> elif event.keysym == 'Down':
>> buttons[index + 1].focus_set()
>> except IndexError:
>> for i in range(len(buttons)-1):
>> buttons[i].bind("<Down>", callback)
>> for i in range(1, len(buttons)):
>> buttons[i].bind("<Up>", callback)
>> I hope this helps
>> .-.. .. ...- . .-.. --- -. --. .- -. -.. .--. .-. --- ... .--. . .-.
>> Wait! You have not been prepared!
>> -- Mr. Atoz, "Tomorrow is Yesterday", stardate 3113.2
>> Tkinter-discuss mailing list
>> Tkinter-discuss at python.org
> View this message in context: http://old.nabble.com/Can%27t-do-proper-event-binding-in-a-for-loop-tp29995174p29999446.html
> Sent from the Python - tkinter-discuss mailing list archive at Nabble.com.
> Tkinter-discuss mailing list
> Tkinter-discuss at python.org
More information about the Tkinter-discuss