首页 > 解决方案 > 无法使用函数更新 tkinter 中的图像

问题描述

我正在尝试创建一个 Tkinter 来创建一个使用标签显示图像的窗口,然后使用更新功能更新图像,但是我试图显示的图像没有显示在 Tkinter 窗口中,而是显示为黑色出现画面

我有两个工作代码

  1. 在 Tkinter 窗口上显示图像的一个
  2. 一种使用更新功能循环 GIF 的东西

我试图将它们结合起来

我正在处理的代码不起作用

#import GUI
from tkinter import *

#change dir
import os
os.chdir("C:/Users/user/Desktop/test image folder/")

#add delay
import time

#import image
from PIL import Image, ImageTk

#set up the window
window = Tk()
#window.title("modify images")

#list of filename
filelist = []

#loop over all files in the working directory
for filename in os.listdir("."):
    if not (filename.endswith('.png') or filename.endswith('.jpg')):
        continue #skip non-image files and the logo file itself
    filelist = filelist + [filename]

#list of filename
print(filelist)

#show first pic
imagefile = filelist[0]
photo = ImageTk.PhotoImage(Image.open(imagefile))
label1 = Label(window, image = photo)
label1.pack()

#update image
def update(ind):
    imagefile = filelist[ind]
    im = ImageTk.PhotoImage(Image.open(imagefile))
    if ind < len(filelist):
        ind += 1
    else:
        ind = 0
    label1.configure(image=im)
    window.after(2000, update, ind)
window.after(2000, update, 0)

#run the main loop
window.mainloop()

我试图结合的其他代码

1:显示图像的那个

import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)


window = tk.Tk()
imagefile = "image.jpg"
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
print('hi')

2:更新gif

from tkinter import *

#change dir
import os
os.chdir("C:/Users/user/Desktop/Learn Python")

#add delay
import time

##### main:
window = Tk()

##### My Photo
photo1 = [PhotoImage(file="anime.gif", format="gif -index %i" %(i)) for i in range(85)]

#update image
def update(ind):
    frame = photo1[ind]
    if ind < 84:
        ind += 1
    else:
        ind = 0
    label.configure(image=frame)
    window.after(80, update, ind)
label = Label(window, bg="black")
label.pack()
window.after(0, update, 0)

#####run the main loop
window.mainloop()

我希望它一张一张地显示文件中的所有图像

它只显示第一张图像,然后窗口变为空白

标签: pythonpython-3.xtkinter

解决方案


你有问题,因为PhotoImage. 如果您在函数中创建它并分配给局部变量,然后Garbage Collector从内存中删除图像,您会看到空图像。您必须创建PhotoImages外部函数,或者必须将其分配给某个全局变量。

流行的解决方案是将其分配给将显示它的标签。

label.im = im

功能:

def update(ind):
    imagefile = filelist[ind]
    im = ImageTk.PhotoImage(Image.open(imagefile))

    if ind < len(filelist):
        ind += 1
    else:
        ind = 0

    label1.configure(image=im)

    label1.im = im  # <-- solution

    window.after(2000, update, ind)

文档:PhotoImage


推荐阅读