我有一個在線托管的影片 .webp 檔案,我嘗試使用 Tkinter 顯示它。這是我的代碼。
import urllib.request
from PIL import Image, ImageTk
root=tkinter.Tk()
u = urllib.request.urlopen("https://..../.....webp")
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
image = ImageTk.PhotoImage(im.resize((470,210)))
Label(root,image=image).pack()
root.mainloop()
這可以在不引發任何錯誤的情況下作業,但只顯示一幀。為什么會這樣?有什么辦法可以解決這個問題
uj5u.com熱心網友回復:
基于@Atlas435 的評論,我制作了一個代碼,它可以在 tkinter 中顯示 webp 檔案而無需下載它們。這是代碼:
from io import BytesIO
from tkinter import *
import tkinter
import urllib.request
from PIL import Image, ImageTk
root=tkinter.Tk()
ar=0
import tkinter as tk
from PIL import Image, ImageTk
u = urllib.request.urlopen(url)
raw_data = u.read()
u.close()
im = Image.open(BytesIO(raw_data))
from itertools import count
class ImageLabel(tk.Label):
"""a label that displays images, and plays them if they are gifs"""
def load(self, im):
if isinstance(im, str):
im = im
self.loc = 0
self.frames = []
try:
for i in count(1):
self.frames.append(ImageTk.PhotoImage(im.copy().resize((470,210))))
im.seek(i)
except EOFError:
pass
try:
self.delay = im.info['duration']
except:
self.delay = 100
if len(self.frames) == 1:
self.config(image=self.frames[0])
else:
self.next_frame()
def unload(self):
self.config(image="")
self.frames = None
def next_frame(self):
if self.frames:
self.loc = 1
self.loc %= len(self.frames)
self.config(image=self.frames[self.loc])
self.after(self.delay, self.next_frame)
lbl = ImageLabel(root)
lbl.pack()
lbl.load(im)
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323751.html
下一篇:Tkinter增量計時器
