[Tkinter-discuss] Re: passing parameters to a lambda function inTkinter menubar

Fredrik Lundh fredrik at pythonware.com
Sat Sep 25 08:55:40 CEST 2004


stewart at midtoad.homelinux.org wrote:

> However, the Options > Set size To menu choice, which uses a lambda function to
> pass the size string to a setFont method, does not work.  It looks as though the
> lambda function doesn't know it's part of the Demo class, so it can't find the
> self.setFont method.  If I replace 'self' with the name of the class, Demo, I
> instead get an error saying 'unbound method must be called with class instance
> 1st argument'.

the lambda isn't part of the class, it's a function object.  to be able to
find the right self, bind it just like you bind the size value.

            menuBar.addmenuitem('Size', 'command', 'Set size to ' + size,
                                command = lambda self=self, ss=size: self.setFont(ss),
                                font=self.font,
                                label = size)

according to the "functions are cheap, lambdas are hard to read" rule,
this is better written as:

            def setfontsize(self=self, size=size):
                self.setFont(size)
            menuBar.addmenuitem('Size', 'command', 'Set size to ' + size,
                                command = setfontsize, font=self.font, label = size)

also see:

http://groups.google.com/groups?selm=mailman.1011942158.19361.python-list%40python.org

</F> 





More information about the Tkinter-discuss mailing list