ttk.Label – Load JPG image from URL

We can download a JPG file and show it in a label.

We do this by downloading the file into a binary stream (BytesIO) using requests.get

We do this by downloading the file into a binary stream (BytesIO) using requests.get

Snippet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Download the image into memory (binary stream).
binary_stream = download_file(url)

# Load image from binary stream
with Image.open(binary_stream) as img:

    # Convert the image into a format that Tk can work with.
    tk_pizza = ImageTk.PhotoImage(image=img)

# Show the image
lbl_test = ttk.Label(root, image=tk_pizza)

Full code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import requests
import tkinter as tk
from tkinter import ttk
from io import BytesIO
from PIL import Image, ImageTk


def download_file(url) -> BytesIO:
    """
    Download a file in chunks and return the finished download
    as a binary stream (BytesIO).
    """
    try:

        # Initialize
        r: requests.models.Response = requests.get(
            url=url, stream=True)

        mystream = BytesIO()

        # Chunk download
        for chunk in r.iter_content(chunk_size=128):

            # Write the downloaded chunk to the stream variable.
            mystream.write(chunk)

        return mystream

    except requests.exceptions.ConnectionError as e:
        print(f"Connection error: {e}")

url = r"https://some_valid_url_here/pizza.jpg"

root = tk.Tk()

binary_stream = download_file(url)

# Load image from binary stream
with Image.open(binary_stream) as img:

    # Convert the image into a format that Tk can work with.
    tk_pizza = ImageTk.PhotoImage(image=img)

# Show the image
lbl_test = ttk.Label(root, image=tk_pizza)
lbl_test.pack()

root.mainloop()