python - Tkinter 动画将不起作用

标签 python animation tkinter gif

我正在尝试显示我的 gif 图像中的动画。来 self 之前的 question ,我发现 Tkinter 不会自动为图像制作动画。我的 Tk 界面显示图像的第一帧,当我点击按钮播放它的动画时,它什么也没做。这可能与与按钮关联的命令有关。这是代码:

from Tkinter import *
import Tkinter

root = Tk()

photo_path = "/users/zinedine/downloads/091.gif"
photo = PhotoImage(
    file = photo_path
    )

def run():
    frame = 1
    while True:
        try:
            photo = PhotoImage(
                file = photo_path,
                format = "gif - {}".format(frame)
                )
            frame = frame + 1

        except Exception: # This because I don't know what exception it would raise
            frame = 1
            break

picture = Label(image = photo)
picture.pack()
picture.configure(run())

animate = Button(
    root,
    text = "animate",
    command = run()
    )
animate.pack()

root.geometry("250x250+100+100")
root.mainloop()

最佳答案

您可以使用通用 Tk 小部件 after()方法来安排函数在以毫秒为单位的指定延迟后运行。这只会发生一次,因此通常函数本身也会调用 after() 来延续该过程。

在下面的代码中定义了一个自定义的 AnimatedGif 容器类,它在一个列表中分别加载和保存动画序列的所有帧,允许使用 [] 快速(随机)访问它们 索引语法。它使用 photo Tk manual page 中提到的 -index indexvalue 图像格式子选项从文件中读取单个帧.

我得到了 test image下图来自 Animation Library网站。

test image

这是它最初启动时的样子。

screenshot of program window at start up

您应该能够使用相同的技术为多个图像或附加到其他类型的小部件(例如 ButtonCanvas 实例)的图像设置动画。

try:
    from tkinter import *
except ImportError:
    from Tkinter import *  # Python 2


class AnimatedGif(object):
    """ Animated GIF Image Container. """
    def __init__(self, image_file_path):
        # Read in all the frames of a multi-frame gif image.
        self._frames = []

        frame_num = 0  # Number of next frame to read.
        while True:
            try:
                frame = PhotoImage(file=image_file_path,
                                   format="gif -index {}".format(frame_num))
            except TclError:
                break
            self._frames.append(frame)
            frame_num += 1

    def __len__(self):
        return len(self._frames)

    def __getitem__(self, frame_num):
        return self._frames[frame_num]


def update_label_image(label, ani_img, ms_delay, frame_num):
    global cancel_id
    label.configure(image=ani_img[frame_num])
    frame_num = (frame_num+1) % len(ani_img)
    cancel_id = root.after(
        ms_delay, update_label_image, label, ani_img, ms_delay, frame_num)

def enable_animation():
    global cancel_id
    if cancel_id is None:  # Animation not started?
        ms_delay = 1000 // len(ani_img)  # Show all frames in 1000 ms.
        cancel_id = root.after(
            ms_delay, update_label_image, animation, ani_img, ms_delay, 0)

def cancel_animation():
    global cancel_id
    if cancel_id is not None:  # Animation started?
        root.after_cancel(cancel_id)
        cancel_id = None


root = Tk()
root.title("Animation Demo")
root.geometry("250x125+100+100")
ani_img = AnimatedGif("small_globe.gif")
cancel_id = None

animation = Label(image=ani_img[0])  # Display first frame initially.
animation.pack()
Button(root, text="start animation", command=enable_animation).pack()
Button(root, text="stop animation", command=cancel_animation).pack()
Button(root, text="exit", command=root.quit).pack()

root.mainloop()

关于python - Tkinter 动画将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28531415/

相关文章:

python - 从源代码构建 python 时如何忽略本地 python

python - 讲解Z阶曲线的代码

CSS3 动画运行延迟动画,所有部分都有全局延迟

python-2.7 - PhotoImage 实例没有属性 'resize'

python - 如何使用全局变量的值来确定在单独线程中运行的函数的控制流?

python - 登录站点的 asyncio post 请求

jquery Sprite 动画响应式

jQuery 动画从 CSS "top"到 "bottom"

python - 从条目中获取一个整数

python - Tkinter 自动重载函数每次调用时都会生成新循环