0

I am trying to add a global shortcut to a gtk.MenuItem which has a sub menu.

Here is my code:

import pygtk, gtk
import keybinder

dlg = gtk.Dialog('menu test')
dlg.set_size_request(200, 40)

menubar = gtk.MenuBar()
menubar.show()
menuitem = gtk.MenuItem('foo')
menuitem.show()
menubar.append(menuitem)

mitem = gtk.MenuItem('bar')
mitem.show()
menu = gtk.Menu()
menu.add(mitem)
menu.show()
menuitem.set_submenu(menu)

def show_menu_cb():
    menubar.select_item(menuitem)

keybinder.bind('<Super>i', show_menu_cb)

dlg.vbox.pack_start(menubar)
dlg.show()
dlg.run()

When I press the key menu pops up, I can then select items in the sub menu or press Esc to make it disappear. But after that the menuitem keeps selected and other windows never get input focus again. I have to click on the menuitem twice to get everything back normal.

1
  • Done. I was just not sure if I should answer my own question :) Commented Dec 30, 2010 at 4:45

1 Answer 1

1

I figured this out. MenuShell.select_item will make the specified menuitem grab the focus, but after the selection inside the menuitem is done, it's necessary to explicitly ungrab the keyboard and mouse focus. So the code looks like:

def on_done(w, *args):
    gtk.gdk.keyboard_ungrab()
    gtk.gdk.pointer_ungrab()

def show_menu_cb():
    menubar.connect('cancel', on_done)
    menubar.connect('selection-done', on_done)
    menubar.select_item(menuitem)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.