Lorenzo Hsu
Lorenzo Hsu

Reputation: 43

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 image. I researched for many methods on displaying that image on a Tkinter Widget but none of them work. It displays the size of the image but not the image itself. This is my code. Thank you very much.

from tkinter import *
from PIL import ImageTk, Image
import requests
import urllib.request
import base64

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


link = "https://tile.openweathermap.org/map/pressure_new/0/0/0.png?appid={APIkey}"

class WebImage:
     def __init__(self,url):
          u = urllib.request.urlopen(url)
          raw_data = u.read()
          u.close()
          self.image = PhotoImage(data=base64.encodebytes(raw_data))

     def get(self):
          return self.image

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

root.mainloop()

Upvotes: 3

Views: 5055

Answers (2)

acw1668
acw1668

Reputation: 46688

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()

Upvotes: 3

JacksonPro
JacksonPro

Reputation: 3275

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()

Upvotes: 1

Related Questions