首页 > 解决方案 > python - 如何使用 tkinter gui 转到幻灯片中的下一张图片

问题描述

我正在尝试制作照片幻灯片程序。它不起作用,因为我想使用 self.counter 变量转到列表中的下一张照片,但是 self.counter 的值会回到 0,因为它忘记了我更改了值的事实。我不认为我可以使用配置,因为然后转到下一个图像的按钮也不起作用。

我希望你能帮助:) 非常感谢。

from tkinter import *

class SlideShowGUI:

    def __init__(self, parent, counter = 0):
        
        self.counter = counter
        
        self.images_list = ["smiley.png", "carrot.png", "bunny.jpg"]
        self.photo = PhotoImage(file = self.images_list[self.counter])

        self.b1 = Button(parent, text = "", image = self.photo, bg = "white")
        self.b1.grid(row = 0, column = 0)
        
        back = Button(parent, width = 2, anchor = W, text = "<", relief = RIDGE, command = self.previous_image)
        back.grid(row = 1, column = 0)
        
        forward = Button(parent, width = 2, anchor = E, text = ">", relief = RIDGE, command = self.next_image)
        forward.grid(row = 1, column = 1)

    def previous_image(self):
        self.counter -= 1
        self.photo.configure(file = self.images_list[self.counter])        

    def next_image(self):
        self.counter += 1
        self.photo.configure(file = self.images_list[self.counter])  

#main routine

if __name__ == "__main__":
    root = Tk()
    root.title("hello")
    slides = SlideShowGUI(root)
    root.mainloop()

抱歉,如果不获取图像,它将无法工作!

在此处输入图像描述

如果我单击下一步按钮两次,则会出现错误消息

标签: pythonfunctiontkintercounterslideshow

解决方案


改用这个:

def previous_image(self):
        self.counter -= 1
        self.photo.configure(file = images_list[self.counter])        

    def next_image(self):
        self.counter += 1
        self.photo.configure(file = images_list[self.counter])

除了你必须注意List Out Of Index错误

另外你为什么要使用global images_list?似乎没有任何意义。如果您想在类中重用该列表,您可以直接命名它self.images_list = [your, items]

你得到的错误:阅读这个


推荐阅读