Newbie (faq!): pmw/tkinter menubar command-option

Martin Rand hsl at tcp.co.uk
Fri Aug 4 08:26:18 EDT 2000


On Fri, 04 Aug 2000 11:15:51 +0200, Brian Elmegaard <be at et.dtu.dk>
wrote:

>Hi,
>
>probably I should be able to find an answer to this in the introduction
>to tkinter/life preserver or in the pmw docs, but I could not manage,
>so:
>
>If I create a menubar using pmw in the __init__-method, and assign a
>command to it, the command is run once during application startup and is
>not available under execution. This is happening only if the function is
>called with an argument or an empty argument list. 
>
>
>The code below act like describd. Why is this happening? How do I avoid
>it and where could I have read about it?
>
>Furthermore, how do I convince pmw to add a tearoff to the menu? (The
>code below only uses tkinter and does add tearoffs)
>
># File: menu1.py
>from Tkinter import *
>def callback(text):
>    print "called the callback!"+text
>root = Tk()
># create a menu
>menu = Menu(root)
>root.config(menu=menu)
>filemenu = Menu(menu)
>menu.add_cascade(label="File", menu=filemenu)
>filemenu.add_command(label="New", command=callback('new'))
>filemenu.add_command(label="Open...", command=callback('open'))
>filemenu.add_separator()
>filemenu.add_command(label="Exit", command=callback('exit'))
>helpmenu = Menu(menu)
>menu.add_cascade(label="Help", menu=helpmenu)
>helpmenu.add_command(label="About...", command=callback('About'))
>
>mainloop()
>
When you assign to the 'command' argument, you need to pass a
*reference* to a function; but what you are doing is passing the
result of *invoking* the function when you construct the menu. In this
example the function doesn't return a result, so 'command' gets
assigned 'None' in each case. (And so never tries to do anything for
the callback.)

Since in this artificial example (and some real-life ones) you may
want to pass a parameter to a common function, you can construct an
anonymous "wrapper" function to look after the specific parameter
generation, using a lambda expression. For instance:

filemenu.add_command(label="New", command=lambda: callback('new'))

On the other hand, if you do have a parameterless procedure as your
callback, you can just write

def callbacknew():
	...

filemenu.add_command(label="New", command=callbacknew)

(Note no parentheses following the function name.)


--
Martin Rand
Highfield Software Ltd
mwr at highfield-software.co.uk
Phone: +44 (0)23 8025 2445
Fax:   +44 (0)23 8025 2445



More information about the Python-list mailing list