Search code examples
onclickclickwxpython

wxPython: Detecting mouse click on a bitmap


I'm trying to detect a clic on a bitmap with wxpython. The on_click procedure seems to run without clic, and not to run when clicking. What do I do wrong?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import os
import wx
import wx.lib.agw.thumbnailctrl as TC
import Image

filename="Raphael-Poli-angle.png"
class MyForm(wx.Frame):
    def on_clic(self):
       print "clicked"

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Choose Dot in Picture", size=(700,500))
        self.panel = wx.Panel(self, wx.ID_ANY)
        png = wx.Image(filename, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        image=wx.StaticBitmap(self.panel, -1, png, (1, 1), (png.GetWidth(), png.GetHeight()))
        image.Bind(wx.EVT_LEFT_DOWN, self.on_clic())
        self.Show(True)

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    app.SetTopWindow(frame)
    frame.Show()
    app.MainLoop()

Solution

  • You do not have to "input an event". The event comes from outside - depending on your action. Change the "def on_clic..." to

      def on_clic(self, evt):
    

    and also change "image.Bind..." to

        image.Bind(wx.EVT_LEFT_DOWN, self.on_clic)
    

    And if you change your on_clic to:

    def on_clic(self, evt):
      x, y=evt.GetPosition()
      print "clicked at", x, y
    

    ...you can also get the position, where the image was clicked.

    See: https://wxpython.org/docs/api/wx.MouseEvent-class.html