python: Right Click on list menu not showing item selected

馋奶兔 提交于 2019-12-23 17:49:16

问题


In my ongoing effort to learn more about python, I am trying to add a right click event to my mp3 manager program. What currently works is that it shows the menu and all of the options. What is not working is the functions selected from the menu are not executing as I think they should be. Much of this code was taken from a 'how to' on another site.

Here are the right click menu options

menu_titles = ["Remove Selection from list",
               "Delete Selection from system",
               "Move Selection",
               "Copy Selection",
               "Print Selection"]

menu_title_by_id = {}
for title in menu_titles:
    menu_title_by_id[ wxNewId() ] = title

The code that is run when the right click event happens

def RightClickCb( self, event ):
    # record what was clicked
    self.list_item_clicked = right_click_context = event.GetText()

    ### 2. Launcher creates wxMenu. ###
    menu = wxMenu()
    for (id,title) in menu_title_by_id.items():
        ### 3. Launcher packs menu with Append. ###
        menu.Append( id, title )
        ### 4. Launcher registers menu handlers with EVT_MENU, on the menu. ###
        EVT_MENU( menu, id, self.MenuSelectionCb )

    ### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
    self.MainPanel.PopupMenu( menu, event.GetPoint() )
    menu.Destroy() # destroy to avoid mem leak

def MenuSelectionCb( self, event ):
    # do something
    operation = menu_title_by_id[ event.GetId() ]
    target    = self.list_item_clicked
    print 'Perform "%(operation)s" on "%(target)s."' % vars()

What I expect to get when I do a right-click and then select one of the options in the menu is the output

Perform "Print Selection" on "<data about the selection here>"

What I am getting is

Perform "Print Selection" on "."

How do I get the data from the item I have selected as part of my right click event?


回答1:


Maybe you should use event.GetString() in place of event.GetText()

See here

Your code seems outdated tho, binding to events should be done like this:

menu.Bind(wx.EVT_MENU, self.MenuSelectionCb, id=id)

moreover if you bind all ids to the same function you can just bind once for all ids:

menu.Bind(wx.EVT_MENU, self.MenuSelectionCb)



回答2:


You can find a solution under Python: Right click on objectlistview not showing item name selected where the use of objectlistview's GetSelectedObject() method is proposed instead.



来源:https://stackoverflow.com/questions/5460030/python-right-click-on-list-menu-not-showing-item-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!