python-3.x - 使用 PIL 动画 gif W/O

标签 python-3.x tkinter tkinter-canvas

我目前正在尝试通过让代码将所有帧拉入我的代码并执行动画来让生活更轻松。我当前的代码是:

import time
from tkinter import *
import os



root = Tk()


imagelist = []
for file in os.listdir("MY-DIRECTORY"):
    if file.endswith(".gif"):
        imagelist.append(PhotoImage(file=str(os.path.join("MY-DIRECTORY", file))))


# extract width and height info
photo = PhotoImage(file=imagelist[0])
width = photo.width()
height = photo.height()
canvas = Canvas(width=width, height=height)
canvas.pack()
# create a list of image objects
giflist = []
for imagefile in imagelist:
    photo = PhotoImage(file=imagefile)
    giflist.append(photo)
# loop through the gif image objects for a while
for k in range(0, 1000):
    for gif in giflist:
        canvas.create_image(width / 2.0, height / 2.0, image=gif)
        canvas.update()
        time.sleep(0.1)
root.mainloop()

当我尝试执行该文件时,它给了我一个我无法理解的错误。

Traceback (most recent call last):
  File "C:/Users/Profile/Desktop/folder (2.22.2019)/animation2.py", line 21, in <module>
    photo = PhotoImage(file=imagelist[0])
  File "C:\Users\Profile\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3545, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\Profile\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 3501, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "pyimage1": no such file or directory

注意:我正在调整这段代码以满足我的需要,这不是我写的。

我运行了一些打印语句来验证 pyimage 是否已上传到阵列,但我不明白为什么它说没有这样的文件或目录,如果它已经上传到阵列。你们都可以发光吗?

最佳答案

我发现我在代码的较低部分创建了一个不必要的对象数组。 giflist[]。我最终解决了这个问题,方法是删除它并让循环使用之前在代码 imagelist 中创建的数组。以下代码现在有效。

import time
from tkinter import *
import os

root = Tk()  

imagelist = []
for file in os.listdir("My-Directory"):
    if file.endswith(".gif"):
        imagelist.append(PhotoImage(file=str(os.path.join("My-Directory", file))))

# Extract width and height info
photo = PhotoImage(file="My-Directory")
width = photo.width()
height = photo.height()
canvas = Canvas(width=width, height=height)
canvas.pack()

# Loop through the gif image objects for a while
for k in range(0, len(imagelist)):
    for gif in imagelist:
        canvas.create_image(width / 2.0, height / 2.0, image=gif)
        canvas.update()
        time.sleep(0.1)
root.mainloop()

关于python-3.x - 使用 PIL 动画 gif W/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54857147/

相关文章:

python - 在 Python 中读取阿拉伯文文件

Python 将宏添加到现有 XLSM

python - 如何从异步函数返回值

python - 如何在 Tkinter 应用程序上运行 unittest?

python - 在 tkinter 上的同一窗口中绘制图形和表格

python - 在多个 Tkinter LabelFrames 之间使用网格对齐小部件

python-3.x - 无效的命令名称 ".!canvas"

python - tkinter:按下按钮添加新图像错误

python - 调整 tkinter 窗口大小以实现全屏

python - 我无法从 Mac 上的 Jupyter 笔记本或 Jupyter Lab 导入 psycopg2。我干净安装了 Catalina