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")