在 Tkinter 中同时多线程处理 Progressbar 和 gif

Multithreading Progressbar and gif simultaneously in Tkinter

我正在尝试将我放入标签 Tkinter 小部件和进度条中的 gif 动画线程化,以便在执行脚本时它们同时 运行。此后,我想使用 time.sleep(10) 让它们同时 运行 10 秒,然后让进度条停止使用 progressbar.stop()。我的代码如下:

import tkinter
from tkinter import ttk
from tkinter import *
import time
from PIL import Image, ImageTk
from itertools import count
import threading


def main_fun():

    global progressbar, lbl
    window = tkinter.Tk()
    window.geometry("390x600")  # Width x Height

    # progress bar
    progressbar = ttk.Progressbar(None)  # ttk is method inside tkinter
    progressbar.config(orient="horizontal",
                       mode='indeterminate', maximum=100, value=0)
    progressbar.pack(side=TOP)

    # gif image class
    class ImageLabel(tkinter.Label):
        """a label that displays images, and plays them if they are gifs"""

        def load(self, im):
            if isinstance(im, str):
                im = Image.open(im)
            self.loc = 0
            self.frames = []

            try:
                for i in count(1):
                    self.frames.append(ImageTk.PhotoImage(im.copy()))
                    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=None)
            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(window)
    lbl.pack(anchor="center")
    lbl.load(
        'C:/Users/*****/test.gif')

    # thread the label with the gif
    t = threading.Thread(target=lbl, args=(None,))
    t.start()

    window.mainloop()


main_fun()


progressbar.start(8)  # 8 is for speed of bounce
t = threading.Thread(target=progressbar, args=(None,)
                     )  # thread the progressbar
#t.daemon = True
t.start()

time.sleep(10)  # 10 second delay, then progressbar must stop
progressbar.stop()

我不熟悉线程,所以我不明白我做错了什么。我收到错误:

TypeError: 'ImageLabel' object is not callable

TypeError: 'progressbar' object is not callable

请协助。

您可以使用 answer given here to implement the progress bar on another thread. Also, what was wrong with what you did is that your progressbar isn't a callable object, nor does it override the run() method.