Search code examples
pythonwxpythoncustom-cursor

How do I create a custom cursor with a custom hotspot in wxPython?


I was trying to create a custom cursor with a custom hotspot (i.e. tip location) in my wxPython application and had some difficulty finding good examples and explanations for how wxPython and wxWidgets handles creating and using cursors. My solution is below.


Solution

  • The cursor I was trying to create needed a different "hotspot" (e.g. tip location). The first discovery I made is that wxPython Image's have an option to set the x and y coordinates of the hotspot. However, wxPython's Cursor class only uses those hotspots if using specific file types.

    From wx.Cursor init documentation they explain...

    The arguments hotSpotX and hotSpotY are only used when there’s no hotspot info in the resource/image-file to load (e.g. when using BITMAP_TYPE_ICO under wxMSW or BITMAP_TYPE_XPM under wxGTK).

    In order to use a custom hotspot, I converted my PNG image to an ICO file using an online converter. Then I was able to use the following code to create a custom cursor with the correct hotspot:

    # The point (6, 28) is the location of my hotspot. This is in reference
    # to the top left corner of the image.
    cursor = wx.Cursor(os.path.join("path", "to", "cursor.ico"), wx.BITMAP_TYPE_ICO, 6, 28)
    frame.SetCursor(cursor)