【发布时间】:2021-09-10 08:29:33
【问题描述】:
我有一个图像列表,我想要的是当我单击一个按钮时,标签上的图像会从列表中的上一个或下一个更改。有任何想法吗?这是我的代码:
from tkinter import *
def left():
dogImg = PhotoImage(file=dogList[index-1])
index -=1
dog.configure(image = dogImg)
def right():
dogImg = PhotoImage(file=dogList[index-1])
index += 1
dog.configure(image = dogImg)
window = Tk()
window.configure(bg='dark turquoise')
window.geometry('500x700')
dogList = ['fox-terrier.png', 'afganHound.png', 'pug.png', 'bulldog.png']
index = 0
dogImg = PhotoImage(file= dogList [index])
dog = Label(window, image = dogImg)
Left = Button(window, text='<-', command=left)
Right = Button(window, text='->', command=right)
Left.place(x = 250, y = 340)
dog.place(x = 280, y = 340)
Right.place(x = 320, y = 340)
window.mainloop()
【问题讨论】:
-
当你运行这段代码时会发生什么?
-
您确实有一个错误,因为您在两个函数中都有
index-1。您应该首先增加/减少索引,然后在 PhotoImage 调用中使用index。并且您可能想检查您是否已从列表的任一端退出。
标签: python python-3.x image tkinter button