gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:03:04 26 4
gpt4 key购买 nike

我有这个向前箭头按钮,点击后应该会在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com