我正在尝试使用 Tkinter 构建图像查看器,但我遇到了这个奇怪的问题

I am trying to build an image viewer using Tkinter but I am stuck at this weird problem

我有这个向前箭头按钮,单击它时应该会显示 picturesList 中的下一张图片。初始图像工作正常,但当我点击前进按钮时,我得到了这个。

Before Clicking

After Clicking:

我正在添加整个代码,因为我真的无法理解问题到底出在哪里,对此深表歉意。

from tkinter import *
from PIL import ImageTk, Image
import os

def moveForward():
    global currImageIndex
    global imgLabel
    currImageIndex += 1

    imgLabel.grid_forget()
    print(picturesList)
    img = ImageTk.PhotoImage(Image.open(picturesList[currImageIndex]))
    imgLabel = Label(root,image=img)
    imgLabel.grid(row=0,column=1)

picturesList = []
for pictures in os.listdir('images'):
    if pictures.startswith('img'):
        picturesList.append('images/'+pictures)

currImageIndex = 0

root = Tk()

img = ImageTk.PhotoImage(Image.open("images/img5.jpg"))
imgLabel = Label(image=img)
imgLabel.grid(row=0,column=1)

backwardImg = ImageTk.PhotoImage(Image.open("images/backward.ico"))
backButton = Button(image=backwardImg,width=80,height=80,relief=FLAT)
backButton.grid(row=0,column=0)


forwardImg = ImageTk.PhotoImage(Image.open("images/forward.ico"))
forwardButton = Button(image=forwardImg, width=80, height=80, relief=FLAT, command=moveForward)
forwardButton.grid(row=0,column=2)

root.mainloop()

保留对图像的引用

from tkinter import *
from PIL import ImageTk, Image
import os

def moveForward():
    global current_img
    global currImageIndex
    global imgLabel
    currImageIndex += 1

    imgLabel.grid_forget()
    print(picturesList)
    img = ImageTk.PhotoImage(Image.open(picturesList[currImageIndex]))
    current_img = img
    imgLabel = Label(root,image=img)
    imgLabel.grid(row=0,column=1)

picturesList = []

#Here is the variable where the reference will be stored
current_img = None
for pictures in os.listdir('images'):
    if pictures.startswith('img'):
        picturesList.append('images/'+pictures)

currImageIndex = 0

root = Tk()

img = ImageTk.PhotoImage(Image.open("images/img5.jpg"))
imgLabel = Label(image=img)
imgLabel.grid(row=0,column=1)

backwardImg = ImageTk.PhotoImage(Image.open("images/backward.ico"))
backButton = Button(image=backwardImg,width=80,height=80,relief=FLAT)
backButton.grid(row=0,column=0)


forwardImg = ImageTk.PhotoImage(Image.open("images/forward.ico"))
forwardButton = Button(image=forwardImg, width=80, height=80, relief=FLAT, command=moveForward)
forwardButton.grid(row=0,column=2)

root.mainloop()