Search code examples
pythonimageurlpopup

Image pop up from a text file in python


I have a text file, where I have multiple image links. I can read that file line by line in Python as hyperlinks. But I am trying to use those links as a pop-up when I will click the link, not to open in a different window. Any tools or any library that I can use?

enter image description here


Solution

  • You can create a JavaScript popup link as follows:

    <a href="some url" target="popup" onclick="window.open('some url','popup','width=w,height=h'); return false;">
    some url
    </a>
    

    In Google Colab you can display HTML from Python using:

    IPython.display.display(HTML(html content))
    

    So you process the file and add the corresponding html to a result variable for each line, then display the full contents.

    MCVE:

    from IPython.display import display, HTML
    
    links = ["https://i.sstatic.net/8lOtO.png", "https://imgs.xkcd.com/comics/helium_reserve.png", "https://i.sstatic.net/gPtbt.jpg"]
    
    def makepopup(link):
      return f"""<a href="{link}" target="popup" onclick="window.open('{link}','popup','width=600,height=200'); return false;">{link}</a><br>"""
    
    linklist = ""
    for link in links:
      linklist += makepopup(link) + "\n"
    
    display(HTML(linklist))
    

    Result (screenshot after clicking the first link): enter image description here

    Note that you do need to provide some fixed width and height, otherwise the popup is just full screen.