Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...