因此,我有一个gif,我需要为它添加动画效果并放入循环中。我可以运行第一个框架,但不能运行下几个框架。仅供参考,gif具有51帧。
import tkinter as tk
window = tk.Tk()
#make label for main page
windowmaintext = tk.Label(window, text="Welcome, to the Supercar Maintenance Calculator")
windowmaintext.grid(column = 1, row = 1)
#make label for main page
windowmaintext2 = tk.Label(window, text="Which super car would you like to explore?")
windowmaintext2.grid(column = 1, row = 2)
#make button to explore AMG cars
start = tk.Button(text= "Mercedes Benz AMG",fg = 'Blue')
start.grid (column = 1, row = 3)
#make button to explore audi cars
start = tk.Button(text= "Audi R8",fg = 'Red')
start.grid (column = 1, row = 4)
#make button to explore Lamborhini cars
start = tk.Button(text= "Lamborghini Huracan",fg = 'Gold')
start.grid (column = 1, row = 5)
#make button to explore Mclaren 720s cars
start = tk.Button(text= "Mclaren 720s",fg = 'Purple')
start.grid (column = 1, row = 6)
#name the window
window.title("Supercar Maintenance Calculator")
#open gif
logo = tk.PhotoImage(file="giphy.gif")
w = tk.Label(window,image=logo).grid(column = 1, row = 7)
#window size
window.geometry("600x600")
#end of page
window.mainloop()
答案 0 :(得分:1)
动画GIF包含许多帧,您必须将每个帧读入PhotoImage。然后,您必须显式播放它们。 Tkinter无法读取帧之间的延迟时间,因此您必须测试不同的值。参见下面的示例:
import tkinter as tk
root = tk.Tk()
framelist = [] # List to hold all the frames
frame_index = 0 # Frame index
while True:
try:
# Read a frame from GIF file
part = 'gif -index {}'.format(frame_index)
frame = tk.PhotoImage(file='images/animated.gif', format=part)
except:
last_frame = frame_index - 1 # Save index for last frame
break # Will break when GIF index is reached
framelist.append(frame)
frame_index += 1 # Next frame index
def animate(frame_number):
if frame_number > last_frame:
frame_number = 0
label.config(image=framelist[frame_number])
root.after(50, animate, frame_number+1)
label = tk.Label(root, bg='#202020')
label.pack()
animate(0) # Start animation
root.mainloop()