how come .insert() don't work

Alex Martelli aleaxit at yahoo.com
Thu Oct 28 04:16:24 EDT 2004


Eric Brunel <eric_brunel at despammed.com> wrote:
    ...
> >         self.html = Menu(self.menubar, tearoff=0)
> >         self.html.add_command(label="p", command=self.tekst_in('p'))
> 
> You're using your tekst_in method before setting the attribute self.tekst, so
> when the method code is executed, there is actully no attribute named tekst;
> hence the Attribute error.

Perfectly true.

> Move the previous line after the self.tekst.pack(...) line and everything
> should be fine.

Nope.  I guess it won't be, because I suspect the OP doesn't actually
mean to insert a 'p' during the __init__ while adding a command of None.

I guess what he means is that, when that menuentry is selected, then and
only then does a 'p' get inserted.  But what he's SAYING is to call the
method right then and there, not set it as a callback as I guess he
means to do.

I think that, to make everything fine, what he needs to do is, rather,
something like:

      ..., command=lambda:self.tekst_in('p'))

For the OP (as I think Eric knows this): 'command' must be set to a
CALLABLE, something Tkinter WILL call without arguments later when
needed; you're setting it to the RESULT of a call that you're doing
yourself, right then and there (and that result is None).  Prepending a
'lambda:' (an unfortunately murky keyword) makes and binds to command a
no-arguments callable, as needed.

It is, of course, very unlikely that method 'self.tekst_in' only ever
needs to be called with that one argument, 'p', or only ever needs to be
bound that way.  If you need to bind callables that will call 'p' with
each of a range of arguments, as would usually be the case, you're
better off forgetting lambda and using closures instead.  Say that,
besides 'p', you also want commands 'q', 'r', 's', 't'.  Then, do:

      self.html = Menu(self.menubar, tearoff=0)
      def make_command(x):
          def callable(): self.tekst_in(x)
          return callable
      for x in 'pqrst':
          self.html.add_command(label=x, command=make_callable(x))


Alex
 



More information about the Python-list mailing list