[Tkinter-discuss] Bind to event related to currently selected menu item

python at bdurham.com python at bdurham.com
Sun Nov 21 18:35:22 CET 2010


Michael,

Thank you! That's EXACTLY the solution I was looking for :)

Regards,
Malcolm

<snipped>
Change your statusbarUpdate for the following, which will print out
the index of the currently selected menu item:

def statusbarUpdate( event=None ):
   print tk.call(event.widget, "index", "active")

Note that this uses tcl/tk code, where Tkinter code should be used,
but it seems the corresponding tkinter code is broken, e.g., with

def statusbarUpdate( event=None ):
   print popup.index('active')

...always returns None on changing the menu selection.

My test code below

from Tkinter import *
import tkFont
tk = Tk()

def statusbarUpdate( event=None ):
   print tk.call(event.widget, "index", "active")

menubar=Menu(tk)
tk.config(menu=menubar)
popup = Menu( menubar )
menubar.add_cascade(label="MyMenu", menu=popup)
popup.bind( '<<MenuSelect>>', statusbarUpdate )
popup.add_command(label="Option 1")
popup.add_command(label="Option 2")
popup.add_command(label="Option 3")
tk.mainloop()


On Sat, Nov 20, 2010 at 11:19 PM,  <python at bdurham.com> wrote:
> Kevin,
>
>> Try <<MenuSelect>>.
>
> Thanks for the recommendation. Any suggestions on how I can determine
> the currently selected menu item in the event raised by <<MenuSelect>>?
>
> # here's how I create my popup menu
> popup = tk.Menu( menubar )
> popup.bind( '<<MenuSelect>>', statusbarUpdate )
>
> # here's the command I bind to
> def statusbarUpdate( event=None ):
>    for key in dir( event ):
>        print key, getattr( event, key )
>
> This outputs the following information as I move between menu items (eg.
> the event is being raised properly).
>
> Note: There seems to be no way to determine the current menu widget
> (event.widget is a string vs. widget reference).
>
> char ??
> delta 0
> height ??
> keycode ??
> keysym ??
> keysym_num ??
> num ??
> send_event False
> serial 238
> state 0
> time 1585806557
> type 35
> widget .#52754872.#52754872#52755392 <-- string vs. widget reference
> width ??
> x 36160384
> x_root 487
> y 53363120
> y_root 307
>
>> Wondering if there's a menu event I can bind to that's related to the
>> currently selected menu item? By menu item I mean the items that show up
>> in a popup menu like New, Open, Save, etc.
>>
>> Use case: I would like to update a statusbar area of our application
>> with a description of the currently selected menu item.
</snipped>



More information about the Tkinter-discuss mailing list