【问题标题】:Getting an image from a list using Tkinter使用 Tkinter 从列表中获取图像
【发布时间】: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


【解决方案1】:

您的代码将起作用,您所要做的就是使函数内部的变量成为全局变量。这是因为在每个函数内部,index 在该函数内部都有作用域,当你声明它们global 时,它会影响函数作用域之外的变量。

def left():
    global dogImg, index                #global variables, else these will be treated as local inside this function
    if index==0:                        #base case, else error will be thrown when clicked left button on 1st picture
        return
    index -=1
    dogImg = PhotoImage(file=dogList[index])
    dog.configure(image = dogImg)


def right():
    global dogImg, index                #global variables, else these will be treated as local inside this function
    if index==len(dogList)-1:           #base case, else error will be thrown when clicked right button on last picture
        return
    index += 1
    dogImg = PhotoImage(file=dogList[index])
    dog.configure(image = dogImg)

另外,只是一个建议,在 Tkinter 中处理图像时,请使用 Pillow 包

from PIL import ImageTk, Image

然后就可以像打开图片了

dogImg = ImageTk.PhotoImage(Image.open(dogList[index]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多