Search code examples
htmlimagejupyter-notebookmarkdownpython-interactive

How to switch between images in interactive way in Jupyter Notebook


If I write the following in my Jupyter Notebook Markdown cell, I get to see an image saved in my "Images" folder

<img src="Images/T1.png"> 

However, I want to switch between 3 images, T1.png, T2.png and T3.png saved in my Images folder interactively by putting some line of code in markdown cell. Can anyone help me do that using Jupyter Notebook markdown cell? I was trying this (that I found on stackoverflow)

<input type="radio" name="T1" class="radio1" checked/>
<input type="radio" name="T2" class="radio2" />
<input type="radio" name="T3" class="radio3" />


<div class="image1">
  <img src="Images/T1.png">
</div>
<div class="image2">
  <img src="Images/T2.png">
</div>
<div class="image3">
  <img src="Images/T3.png">
</div>

But I am getting all the images stacked one after another like this (I want them one at a time on screen): enter image description here

Thanks in advance!


Solution

  • You need some javascript/css, which is not supported by a Markdown cell. Instead just display an HTML document in python. Here you have:

    from IPython.core.display import display, HTML
    
    html = """
        Select an Image:
        <input type="radio" name="images" onclick="show1();" checked>Image 1</input>
        <input type="radio" name="images" onclick="show2();">Image 2</input>
        <input type="radio" name="images" onclick="show3();">Image 3</input>
    
    
        <div id="image1">
          <img src="Images/T1.png">
        </div>
        <div id="image2">
          <img src="Images/T2.png">
        </div>
        <div id="image3">
          <img src="Images/T3.png">
        </div>
        
        <script>
        function show1(){
          document.getElementById('image1').style.display ='block';
          document.getElementById('image2').style.display ='none';
          document.getElementById('image3').style.display ='none';
        }
        function show2(){
          document.getElementById('image2').style.display ='block';
          document.getElementById('image1').style.display ='none';
          document.getElementById('image3').style.display ='none';
        }
        function show3(){
          document.getElementById('image3').style.display ='block';
          document.getElementById('image1').style.display ='none';
          document.getElementById('image2').style.display ='none';
        }
        show1()
        </script>
    """
    display(HTML(html))
    

    enter image description here