Right Click Menu (context menu) using PyGTK

后端 未结 1 1170
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-14 12:30

So I\'m still fairly new to Python, and have been learning for a couple months, but one thing I\'m trying to figure out is say you have a basic window...

#!/usr/         


        
相关标签:
1条回答
  • 2021-02-14 13:15

    There is a example for doing this very thing found at http://www.pygtk.org/pygtk2tutorial/sec-ManualMenuExample.html

    It shows you how to create a menu attach it to a menu bar and also listen for a mouse button click event and popup the very same menu that was created.

    I think this is what you are after.

    EDIT: (added further explanation to show how to respond to only right mouse button events)

    To summarise.

    Create a widget to listen for mouse events on. In this case it's a button.

    button = gtk.Button("A Button")
    

    Create a menu

    menu = gtk.Menu()
    

    Fill it with menu items

    menu_item = gtk.MenuItem("A menu item")
    menu.append(menu_item)
    menu_item.show()
    

    Make the widget listen for mouse press events, attaching the menu to it.

    button.connect_object("event", self.button_press, menu)
    

    Then define the method which handles these events. As is stated in the example in the link, the widget passed to this method is the menu that you want popping up not the widget that is listening for these events.

    def button_press(self, widget, event):
        if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
            #make widget popup
            widget.popup(None, None, None, event.button, event.time)
            pass
    

    You will see that the if statement checks to see if the button was pressed, if that is true it will then check to see which of the buttons was pressed. The event.button is a integer value, representing which mouse button was pressed. So 1 is the left button, 2 is the middle and 3 is the right mouse button. By checking to see if the event.button is 3, you are only responding to mouse press events for the right mouse button.

    0 讨论(0)
提交回复
热议问题