Capture Right Click events in pygtk

Posted in python

If you pass in the event when you enter a callback, you can look at event.type to determine which button was pushed and process the action accordingly.

If you’re only interested in the right-click, say for a menu popup for example, check for event.button equal to three.

def tv_event_cb(widget, event):
    if event.type == gtk.gdk.BUTTON_PRESS:
        if event.button != 3:
            return False

Make sure to check the event.type first for a button press as not all events will define an event.button.

Here’s an example of catching right clicks on a treeview:

#!/usr/bin/env python

import gtk

class Example:
    def __init__(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_size_request(200,200)

        store = gtk.ListStore(str)
        store.append([ 'rootninja' ])

        cell = gtk.CellRendererText()

        tvcol = gtk.TreeViewColumn('col0')
        tvcol.pack_start(cell, True)
        tvcol.add_attribute(cell, 'text', 0)

        tv = gtk.TreeView(store)
        tv.connect('event', self.tv_cb)
        tv.append_column(tvcol)

        window.add(tv)
        window.connect("destroy", gtk.main_quit)
        window.show_all()

    def tv_cb(self, tv, event):
        if event.type == gtk.gdk.BUTTON_PRESS:
            if event.button != 3:
                return
            else:
                print "right button pressed"

Example()
gtk.main()

In this case, connecting the broad ‘event’ enables my callback to use event without having to pass it in, however, most signals all you to specify any arguments you want.

Posted by admica   @   27 July 2011

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional