如何解决tkinter - 加载 gif 直到 def 出来
当我开始这个过程时 def loading(): 已经出来了,直到 print("hello world") 并且在 def loading() 中也没有点击按钮:当我启动 def loading(): 它必须是点击按钮和使用带按钮的命令,但我最后不想那样做,我只想在我开始进程时执行 def loading():首先出现直到 print("hello world") 没有任何点击按钮或点击的东西,请帮帮我>
from PIL import Image
def hi():
time.sleep(10)
print("hello world")
def loading():
root = tk.Tk()
root.configure(bg='white')
file="giphy.gif"
info = Image.open(file)
frames = info.n_frames # gives total number of frames that gif contains
# creating list of PhotoImage objects for each frames
im = [tk.PhotoImage(file=file,format=f"gif -index {i}") for i in range(frames)]
count = 0
anim = None
def animation(count):
global anim
im2 = im[count]
gif_label.configure(image=im2)
count += 2
if count == frames:
count = 0
anim = root.after(100,lambda :animation(count))
gif_label = tk.Label(root,image="",bg='white',)
gif_label.pack()
解决方法
下面的代码显示了一种方法。当 def hi()
函数执行并打印消息时,它现在还会设置一个全局标志变量,执行动画的函数会定期检查该变量。当标志的值发生变化时,它会导致动画停止。
from PIL import Image
import tkinter as tk
stop = False # Global flag.
def hi():
global stop
print("hello world")
stop = True
def loading(filename):
root = tk.Tk()
root.configure(bg='white')
info = Image.open(filename)
frames = info.n_frames # gives total number of frames that gif contains
# creating list of PhotoImage objects for each frames
im = [tk.PhotoImage(file=filename,format=f"gif -index {i}") for i in range(frames)]
count = 0
def animation(count):
frame = im[count]
gif_label.configure(image=frame)
count = (count+1) % frames
if not stop:
root.after(200,lambda: animation(count))
btn = tk.Button(text="Start",command=lambda: animation(count))
btn.pack()
gif_label = tk.Label(root,image="",bg='white',)
gif_label.pack()
root.after(5000,hi) # Call hi() in 5 seconds.
root.mainloop()
loading("small_globe.gif")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。