Displaying images from url in tkinter


Displaying images in Tkinter GUI applications can greatly enhance the visual appeal and user experience. While Tkinter provides various tools for working with images, displaying images directly from a URL requires additional steps. In this article, we will explore how to fetch and display images from URLs in Tkinter using the Python Imaging Library (PIL). We'll learn how to handle URL requests, process the image data, and showcase the images within Tkinter windows. By the end of this article, you'll have a clear understanding of how to dynamically fetch and display images from the web in your Tkinter applications, opening possibilities for incorporating live or remote images into your GUI designs.

Using the PIL Library

To display images from a URL in Tkinter, we need to use the PIL (Python Imaging Library) library. It provides powerful image processing capabilities and supports a wide range of image formats. To install PIL, you can use the following command −

pip install Pillow

Once PIL is installed, we can proceed with the implementation.

# Import neccessary libraries
from PIL import ImageTk, Image
import tkinter as tk
import urllib.request

def display_image_from_url(url):
   with urllib.request.urlopen(url) as u:
      raw_data = u.read()

   image = Image.open(io.BytesIO(raw_data))
   photo = ImageTk.PhotoImage(image)

   # Create a Tkinter window
   root = tk.Tk()

   # Create a label widget to display the image
   label = tk.Label(root, image=photo)
   label.pack()

   # Start the Tkinter event loop
   root.mainloop()

# Example usage
display_image_from_url("https://www.tutorialspoint.com/python_pillow/images/tutorials_point.jpg")

Let's go through the code step by step −

  • We import the necessary libraries − ImageTk and Image from the PIL module, tkinter, and urllib.request.

  • The display_image_from_url function takes a URL as input.

  • We use the urlopen function from urllib.request to fetch the image data from the specified URL.

  • The image data is read as raw bytes.

  • We create an Image object using Image.open, passing a BytesIO object that wraps the raw data.

  • Using ImageTk.PhotoImage, we create a Tkinter-compatible image object.

  • We create a Tkinter window using tk.Tk().

  • We create a Label widget and assign the Tkinter image object to its image parameter.

  • The label is packed into the window using pack().

  • Finally, the Tkinter event loop is started with root.mainloop().

This code fetches an image from the specified URL and displays it in a Tkinter window using a Label widget.

Handling Exceptions

When fetching images from URLs, it's important to handle potential exceptions to prevent crashes or unexpected behavior in your application. Let's modify our previous code to handle exceptions gracefully −

Example

# Import neccessary libraries
from PIL import ImageTk, Image
import tkinter as tk
import urllib.request
import io

# Define function to fetch images from url and exception handling
def display_image_from_url(url):
   root = tk.Tk()
   root.title("Displaying Images from URL in Tkinter")
   root.geometry("700x400")
   try:
      with urllib.request.urlopen(url) as u:
         raw_data = u.read()
   except Exception as e:
      print(f"Error fetching image: {e}")
      return

   try:
      image = Image.open(io.BytesIO(raw_data))
      photo = ImageTk.PhotoImage(image)
   except Exception as e:
      print(f"Error opening image: {e}")
      return
# creating labels and Run the Tkinter event loop 
   
   label = tk.Label(root, image=photo)
   label.pack()
   root.mainloop()

# Example usage
display_image_from_url("https://www.tutorialspoint.com/python_pillow/images/tutorials_point.jpg")

In the above code, we enclose the code that fetches the image and creates the Image and PhotoImage objects within separate try-except blocks. If an exception occurs during these operations, the corresponding error message is printed, and the function returns. This way, we can handle errors gracefully and ensure that the application continues running even if image fetching or processing fails.

Output

After running the above code, you will get the following Tkinter window with the image at the given URL −

Conclusion

In conclusion, displaying images from URLs in Tkinter allows us to bring dynamic and remote images into our GUI applications. By leveraging the power of the Python Imaging Library (PIL) and Tkinter, we can fetch image data from URLs, process it, and showcase it within Tkinter windows using the appropriate widgets. We learned how to handle URL requests, deal with exceptions, and create a visually appealing user interface. With the knowledge gained from this article, you can now enhance your Tkinter applications by incorporating images directly from the web. Whether it's fetching and displaying product images from an online store or showcasing live images from a web camera, the ability to display images from URLs adds versatility and interactivity to your GUI designs. So go ahead and explore the world of remote images in Tkinter to create captivating and dynamic user experiences.

Updated on: 04-Dec-2023

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements