0
How to fade in/out on a Tkinter Frame
此問題顯示您不能使用Tkinter的默認透明度淡入和淡出使用小部件。但是,有沒有其他方式,使用PIL或其他方式在Tkinter中淡出小部件(或圖片)? (即調節透明度)淡入小部件或圖片進出 - Tkinter
How to fade in/out on a Tkinter Frame
此問題顯示您不能使用Tkinter的默認透明度淡入和淡出使用小部件。但是,有沒有其他方式,使用PIL或其他方式在Tkinter中淡出小部件(或圖片)? (即調節透明度)淡入小部件或圖片進出 - Tkinter
(希望)簡單的答案:
#!python3
import tkinter as tk
from PIL import Image, ImageTk
import os
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Image Fading")
self.label = tk.Label(self)
self.label.pack()
self.load_pictures()
self.fadetime = 1 # time between alpha channel changes in ms
self.fadestep = 5 # change to alpha channel
self.curstep = 0 # the current step through the transparency
self.im = None # to hold the raw picture
self.photo = None # to hold the tk compatible picture
self.after(self.fadetime, self.fade_in)
def fade_in(self):
if not self.im:
self.load_picture()
alpha = min(self.curstep * self.fadestep, 255) # clamp to 255 maximum
self.im.putalpha(alpha)
self.photo = ImageTk.PhotoImage(self.im)
self.label.configure(image=self.photo)
self.curstep += 1
print('fade in: %i' % alpha)
if alpha == 255:
self.curstep = 0
self.after(3000, self.fade_out) # wait three seconds then fade out
else:
self.after(self.fadetime, self.fade_in)
def fade_out(self):
alpha = max(255 - self.curstep * self.fadestep, 0) # clamp to 0 minimum
self.im.putalpha(alpha)
self.photo = ImageTk.PhotoImage(self.im)
self.label.configure(image=self.photo)
self.curstep += 1
print('fade out: %i' % alpha)
if alpha == 0:
self.curstep = 0
self.im = None
self.index += 1 # to use next picture
if self.index >= len(self.filenames):
self.index = 0
self.after(3000, self.fade_in) # wait three seconds then load next picture
else:
self.after(self.fadetime, self.fade_out)
def load_picture(self):
while True:
file = open(self.filenames[self.index], mode='rb')
try: # if errors opening file as image, ignore and try next one
self.im = Image.open(file) # this is a lazy operation and only reads image header
self.im.load() # force image load here
file.close() # close the file
print('loaded: %s' % self.filenames[self.index])
break
except:
file.close()
self.index += 1
if self.index >= len(self.filenames):
self.index = 0
def load_pictures(self):
self.filenames = []
for file in os.listdir():
if file.rsplit('.', 1)[-1] not in ['db', 'py', 'pyw']:
self.filenames.append(file)
self.index = -1
if __name__ == '__main__':
app = App()
app.mainloop()
這是假定你想淡出每個圖像出來,然後下一個中而不是從一個到下一直褪色。 請注意,儘管以最簡單的方式(使用putalpha
)完成這種淡入/淡出仍然是cpu密集型的,因爲每個迭代都轉換爲ImageTk
實例。 那就是爲什麼我已經把變量的alpha步長和時間來控制它需要被調用的次數。
如果我的假設是錯誤的,並且您需要從一個直線漸變到下一個,則會更加密集,因爲您需要在將圖像應用到每個圖像後將圖像「融合」在一起,然後將結果到ImageTk
實例
你的假設是正確的,這是有效的。謝謝! – Dova