[英]How to display multiple Images from from multiple urls in a single Tkinter canvas using Python
[英]How to display a photo on a Tkinter App from a URL using canvas
import io
import base64
try:
# Python2
import Tkinter as tk
from urllib2 import urlopen
except ImportError:
# Python3
import tkinter as tk
from urllib.request import urlopen
def display_poster(image_url, x, y):
# image_url = "http://i46.tinypic.com/r9oh0j.gif"
image_byt = urlopen(image_url).read()
image_b64 = base64.encodebytes(image_byt)
photo = tk.PhotoImage(data=image_b64)
# create a white canvas
cv = tk.Canvas(bg='white')
cv.pack(side='top', fill='both', expand='yes')
# put the image on the canvas with
# create_image(xpos, ypos, image, anchor)
cv.create_image(x, y, image=photo, anchor='nw')
def btn_clicked():
display_poster("http://i46.tinypic.com/r9oh0j.gif", 630, 350)
我已經嘗試過base64 package解決方案,但它不起作用。 如果有人可以幫助我解決我需要導入的軟件包和function使用Canvas顯示圖像,那就太好了。
使用這個片段,它的工作正常:
import tkinter as tk
import urllib.request
#import base64
import io
from PIL import ImageTk, Image
root = tk.Tk()
root.title("Weather")
link = "http://i46.tinypic.com/r9oh0j.gif"
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()
Output:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.