[tkinter] Event from menu event?

John Michelsen john.michelsen at gte.net
Tue May 25 00:43:04 EDT 1999


> I have no way of knowing within my
>called function *which* menu item was chosen.
>It sure would be handy to be able to control multiple menu items with
>one function, but how would it tell the events apart??

>
>I know you can use "bind" with buttons to bind a function to an event,
>and that the function gets an event passed to it.  But menus look to be
>different.  I can mymenu.add_command(label = "foo", command = myfunc)
>but if I def myfunc this way:
>
>def myfunc(event):
>    print event
>
>I get:
>
>TypeError: not enough arguments; expected 1, got 0
>
>I know there's just *got* to be a way to write a generalized
>menu-item-handling function.  Certainly *someone* has wanted a menu of,
>say, colors, or bookmark items, or whatever, where the action is the
>same for a group of menu items.


How about this?:

from Tkinter import *
import Pmw

def myfunc():
    print var.get()

root = Tk()
menubar = Pmw.MenuBar(root, hull_borderwidth = 0, hotkeys=1)
menubar.pack(anchor=NW)
menubar.addmenu('File', 'File commands')
var = StringVar()
var.set('First')
menubar.addmenuitem('File', 'radiobutton', label='First', command=myfunc,
    value='First', variable=var)
menubar.addmenuitem('File', 'radiobutton', label ='Second', command=myfunc,
    value='Second', variable=var)
menubar.addmenuitem('File', 'radiobutton', label ='Third', command=myfunc,
    value='Third', variable=var)
menubar.addmenuitem('File', 'radiobutton', label ='Fourth', command=myfunc,
    value='Fourth', variable=var)

root.mainloop()

John






More information about the Python-list mailing list