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

标签 python tkinter pypy

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

Before Clicking

enter image description here

After Clicking:

enter image description here

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

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()

关于python - 我正在尝试使用 Tkinter 构建图像查看器,但我遇到了这个奇怪的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61735195/

相关文章:

python - Jinja2 If 语句

python - 在 Python 中删除日历小部件中的 'Week Number' 列

python - Tkinter - 当写入两个 Entry Widget 时触发事件,无论顺序如何

python - python 内置函数是否总是 C 扩展(即使在 PyPy 上)?

python - Django - 如何在协作项目中处理 settings.py 中的路径

python - USB条码扫描器研究

python - 如何映射两个字典中的相同项目并生成其对应键的值列表

python - 使用 tkinter 和类创建多个不同颜色的形状

python - 如何在 Mac 上使用 PyPy?

python - 为什么 cffi 比 numpy 快这么多?