开发者

Right Click Menu (context menu) using PyGTK

开发者 https://www.devze.com 2023-03-18 15:11 出处:网络
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...

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/bin/env python

import sys, os
import pygtk, gtk, gobject

class app:

   def __init__(self):
    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.set_title("TestApp")
    window.set_default_size(320, 240)
    window.connect("destroy", gtk.main_quit)
    window.show_all()

app()
gtk.main()

I wanna right clic开发者_如何学Ck inside this window, and have a menu pop up like alert, copy, exit, whatever I feel like putting down.

How would I accomplish that?


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

精彩评论

暂无评论...
验证码 换一张
取 消