简体   繁体   中英

Mouse event in DrawingArea with PyGtk

I want to get the X and Y coordinates when I click on a DrawingArea. I was looking for some examples and I found a code like the following

import gtk

class Ventana(gtk.Window):

    def __init__(self):
        super(Ventana, self).__init__()

        self.set_title('Test')
        self.set_size_request(800, 600)
        self.set_position(gtk.WIN_POS_CENTER)
        self.connect('destroy', gtk.main_quit)

        self.drawing_area = gtk.DrawingArea()
        self.drawing_area.set_size_request(780, 500)
        self.drawing_area.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('white'))
        self.drawing_area.connect('button-press-event', self.on_drawing_area_button_press)

        fixed = gtk.Fixed()
        fixed.put(self.drawing_area, 10, 10)

        self.add(fixed)

        self.show_all()

    def on_drawing_area_button_press(self, widget, event):
        print event.x, ' ', event.y


def main():
    Ventana()
    gtk.main()

if __name__ == '__main__':
    main()

When I run it, the window appears and the DrawingArea with the white background, but when I click on it, it doesn't print the values of event.x and event.y and there are no error messages.

Can anyone tell me what is the correct way to do that?

Thanks for answering.

The drawing area needs to be setup with event masks for the events you want to connect to it.

self.drawing_area.set_events(gtk.gdk.BUTTON_PRESS_MASK)

See: http://www.pygtk.org/pygtk2tutorial/sec-EventHandling.html (which also has a good example at the bottom of the page)

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