Search code examples
pythonpython-2.7wxpython

wxPython image with url


I have image in app using wx.StaticBitmap, but I need to add url to image, when you click image it should open that url using default browser of system. How to place such image?


Solution

  • You will need to bind your instance of wx.StaticBitmap to wx.EVT_LEFT_DOWN and use Python's webbrowser module to open the url. You could create a dictionary of images where each image maps to a URL. Then when you load an image, you set a variable to that image's path and use that as your key in the dictionary to load the URL when the image is clicked.

    Here's a fairly simple example:

    import webbrowser
    import wx
    
    ########################################################################
    class ImgPanel(wx.Panel):
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self, parent):
            """Constructor"""
            wx.Panel.__init__(self, parent)
    
            self.my_images = {"/path/to/image.jpg":"www.example.com"}
            self.loaded = "/path/to/image.jpg"
    
            img = wx.Image(self.loaded, wx.BITMAP_TYPE_ANY)
    
            self.image_ctrl = wx.StaticBitmap(self, bitmap=wx.BitmapFromImage(img))
            self.image_ctrl.Bind(wx.EVT_LEFT_DOWN, self.onClick)
    
        #----------------------------------------------------------------------
        def onClick(self, event):
            """"""
            webbrowser.open(self.my_images[self.loaded])
    
    ########################################################################
    class MainFrame(wx.Frame):
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self):
            """Constructor"""
            wx.Frame.__init__(self, None, title="Images")
            panel = ImgPanel(self)
            self.Show()
    
    if __name__ == "__main__":
        app = wx.App(False)
        frame = MainFrame()
        app.MainLoop()