Skip to content Skip to sidebar Skip to footer

Displaying Image From Url In Python/tkinter

I am working on a weather app and to add some spice I was thinking on adding a Weather Map, so reached over to https://openweathermap.org/api/weathermaps and got a URL with the ima

Solution 1:

You code works fine if the image in the link is PNG. May be the image in the link is JPEG which is not supported by tkinter.PhotoImage.

You can use Pillow module which supports various image formats:

import tkinter as tk
import urllib.request
#import base64
import io
from PIL import ImageTk, Image

root = tk.Tk()
root.title("Weather")

link = "https://openweathermap.org/themes/openweathermap/assets/img/logo_white_cropped.png"

class WebImage:
    def __init__(self, url):
        with urllib.request.urlopen(url) as u:
            raw_data = u.read()
        #self.image = tk.PhotoImage(data=base64.encodebytes(raw_data))
        image = Image.open(io.BytesIO(raw_data))
        self.image = ImageTk.PhotoImage(image)

    def get(self):
        return self.image

img = WebImage(link).get()
imagelab = tk.Label(root, image=img)
imagelab.grid(row=0, column=0)

root.mainloop()

Solution 2:

Here try this:

from tkinter import *
from PIL import ImageTk, Image
import requests
from io import BytesIO


root = Tk()
root.title("Weather")


link = "yourlink/image.jpg"

class WebImage:
     def __init__(self,url):
          u = requests.get(url)
          self.image = ImageTk.PhotoImage(Image.open(BytesIO(u.content)))
          
     def get(self):
          return self.image

img = WebImage(link).get()
imagelab = Label(root, image = img)
imagelab.grid(row = 0, column = 0)

root.mainloop()

Post a Comment for "Displaying Image From Url In Python/tkinter"