[Tutor] binding problem

Wayne Werner waynejwerner at gmail.com
Thu Nov 3 16:08:22 CET 2011


On Thu, Nov 3, 2011 at 9:41 AM, Chris Hare <chare at labr.net> wrote:

> Thanks Peter.  Actually, I have read a bunch of stuff and looked at
> example code.  The problem in this case is I am using a defined method -
> focus_set(), which is part of Tkinter and isn't part of my code.  since I
> am using it in the manner in which I have seen other examples, I am
> confused about why it is complaining about 2 arguments, when I am not
> passing any.
>
> Although, I think I know what the problem is now.
>

The problem is that when you use .bind() Tkinter will pass an event into
your function. This event contains useful information such as the x,y
position of your mouse, the key that fired the event, and a few other
items. Of course, since focus_set() belongs to a class it will always pass
'self' as the first parameter.

So when you bind widget.focus_set, when the event loop handles say,
<Button-1>, it finds the function bound (focus_set), and Python passes self
and Tkinter passes the event - two parameters, even though you're passing
none.

As has been touched on, the standard thing to do when you are binding an
event but you don't actually care about the event (like focus_set()), is to
use the lambda, which allows you to ignore the event argument:

self.list.bind("<Button-1>", lambda _: self.login_userid.focus_set())

It's convention to use the _ variable name to tell other programmers that
you don't care about that value, and you're intentionally ignoring whatever
gets passed to that function.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111103/af506733/attachment.html>


More information about the Tutor mailing list