简体   繁体   中英

How do I programmatically pull down a wx.Menu in wxPython

If I have a wx.Menu (in a wx.MenuBar, at the top of a frame, like normal) - how can I cause that menu to drop down and take focus, without clicking on it. I want the behavior to be as if the user had pressed the keyboard accelerator shortcut for that menu (so Alt+F for example, for the &File menu)

I had the same requirement and found the simple way of using the PopupMenu function. It is not called from the menu object but from the parent of the menu (the window, frame, etc..)

To make sure that the menu appears at a specific position, regardless of your mouse, supply to the PopupMenu function a position parameter as well.

In the example bellow, I turned a platebtn that was opening the menu only when clicked in the right side, in the small area of the down arrow, into a button that opens the same menu in the same way when you click it anywhere on its surface.

Example:

import wx
import wx.lib.platebtn as platebtn
class MyFrame(wx.Frame):
    def __init__(self, parent, ID, title):
        wx.Frame.__init__(self, parent, ID, title, size=(300, 250))
        wx.Panel(self,-1, style=wx.SUNKEN_BORDER)
        droparrow = platebtn.PB_STYLE_DROPARROW | platebtn.PB_STYLE_SQUARE | platebtn.PB_STYLE_GRADIENT
        self.btn1 = platebtn.PlateButton(self, wx.ID_ANY, label=" File ", style=droparrow)
        self.btn1.SetPressColor(wx.LIGHT_GREY) 
        self.menu1 = wx.Menu()
        self.menu1.Append(1, "New")
        self.menu1.Append(2, "Open")
        self.menu1.Append(3, "Exit")
        sm = wx.Menu()
        sm.Append(8, "sub item 1")
        sm.Append(9, "sub item 1")
        self.menu1.AppendMenu(7, "Test Submenu", sm)
        self.btn1.SetMenu(self.menu1)
        self.Bind(wx.EVT_BUTTON, self.OnFile, self.btn1)
    def OnFile(self, event):
        self.btn1.PopupMenu(self.menu1, pos=(1, self.btn1.GetSize()[1]))
app = wx.App(False)
frame = MyFrame(None, -1, "PopupMenu example")
frame.Show()
app.MainLoop()

Try with wx.PostEvent :

event = wx.MenuEvent(wx.wxEVT_LEFT_DOWN, menuitem.GetId(), menu)
wx.PostEvent(frame, event)

Other wx mouse events: http://www.wxpython.org/docs/api/wx.MouseEvent-class.html

Found in google groups thread

To define accelerators for menu in your program,Understand through the given example

example:

file_menu=wx.Menu()
menubar=wx.MenuBar()
menubar.Append(file_menu,"&File")  
self.SetMenuBar(menubar)

Now we can access the File menu (here) by pressing ALT+F.

If we have other menus too,on pressing ALT ,it will point to the first Letter of menu bar,from which you can press the next key according to the name of menu_item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM