Tkinter menu commands activate when menu is built

David Mallwitz dmallwitz at cox.rr.com
Fri Nov 9 20:17:43 EST 2001


    This is my first attempt at a program using Tkinter. I'm ok with the
widgets, geometry managers, frames, etc... but the menu bar is giving me
grief.
     According to the documentation 'menu.add_command(label='x', command=y)'
should create a dropdown menu entry named 'x' that will activate function
y() when clicked. The following program builds a basic window with one
dropdown menu that has four entries. The problem is that the function
do_stuff() executes when the menu is built (in the program below, it will
execute 4 times as the root window is being built) rather than when the
widget is clicked on.
    Am I missing something basic here? I get the same behavior from both
Windows and Linux so I figure it's got to be me being stupid, but all my
books and the online docs indicate that this should work. Call the program
(on Windows) from python.exe instead of from pythonw.exe to see the problem.

from Tkinter import *

def do_stuff(port):
 print "In function 'do_stuff(%d)'" % port

### Build the main window
root = Tk()
root.geometry('300x200')

### Construct the Menubar
menubar = Menu(root)
connectmenu = Menu(menubar, tearoff=0)
connectmenu.add_command(label="Example 1", command=do_stuff(1))
connectmenu.add_command(label="Example 2", command=do_stuff(2))
connectmenu.add_command(label="Example 3", command=do_stuff(3))
connectmenu.add_command(label="Example 4", command=do_stuff(4))
menubar.add_cascade(label="Connect", menu=connectmenu)
root.config(menu=menubar)

def main():
 root.mainloop()

if __name__  == '__main__':
 main()


Thanks,
Dave





-----=  Posted via Newsfeeds.Com, Uncensored Usenet News  =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
 Check out our new Unlimited Server. No Download or Time Limits!
-----==  Over 80,000 Newsgroups - 19 Different Servers!  ==-----



More information about the Python-list mailing list