ttk.Label – Load PNG image from URL

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

We don’t need to download the image to the file system – we can download it directly into memory using requests.get and BytesIO.

Tkinter supports PNG image files natively, so there is no need to use the Pillow library to show PNG images.

Snippet

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

# Load the binary stream into an image format that Tkinter can use.
tk_pizza = tk.PhotoImage(data=binary_stream.getvalue())

# 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
import requests
import tkinter as tk
from tkinter import ttk
from io import BytesIO


def download_file(url) -> BytesIO:
    """
    Download the 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.png"

root = tk.Tk()

binary_stream = download_file(url)

# Load the binary stream into an image format that Tkinter can use.
tk_pizza = tk.PhotoImage(data=binary_stream.getvalue())

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

root.mainloop()