Search code examples
pythongtkpygtk

How to get mouse position at mouse click - Python Gtk


I am writing an school project about Graph Theory. I need to implement some Graph algorithms (Dijkstra's, Prim's etc.). After that I need to visualize them in the same program.

I can draw rectangles and line inside a drawing area for visualizing graph. But I need to handle mouse events for make it interactive.

For example when user wanted to add a vertex to the graph, I need the position of mouse.

My native is not English. I couldn't explain my problem great. :)


Solution

  • Use a gtk.EventBox and event'ss x and y fields:

    import gtk
    
    win  = gtk.Window ()
    box  = gtk.EventBox ()
    area = gtk.DrawingArea ()
    
    def onclick (box, event):
       print event.x, event.y
    
    box.connect ('button-press-event', onclick)
    
    box.add (area)
    win.add (box)
    win.show_all ()
    win.connect ('destroy', lambda *x: gtk.main_quit ())
    
    gtk.main ()