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 91011
# Download the image into memory (binary stream).binary_stream=download_file(url)# Load image from binary streamwithImage.open(binary_stream)asimg:# Convert the image into a format that Tk can work with.tk_pizza=ImageTk.PhotoImage(image=img)# Show the imagelbl_test=ttk.Label(root,image=tk_pizza)
importrequestsimporttkinterastkfromtkinterimportttkfromioimportBytesIOfromPILimportImage,ImageTkdefdownload_file(url)->BytesIO:""" Download a file in chunks and return the finished download as a binary stream (BytesIO). """try:# Initializer:requests.models.Response=requests.get(url=url,stream=True)mystream=BytesIO()# Chunk downloadforchunkinr.iter_content(chunk_size=128):# Write the downloaded chunk to the stream variable.mystream.write(chunk)returnmystreamexceptrequests.exceptions.ConnectionErrorase: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 streamwithImage.open(binary_stream)asimg:# Convert the image into a format that Tk can work with.tk_pizza=ImageTk.PhotoImage(image=img)# Show the imagelbl_test=ttk.Label(root,image=tk_pizza)lbl_test.pack()root.mainloop()