Tkinter幻灯片与按钮

时间:2018-01-29 14:03:25

标签: python python-3.x tkinter

我想编写一个幻灯片,在按下按钮后更改图像。我也希望能够在两个方向上改变图像。

显然我发现一些代码有点适合但不完全是我想要的。 class ImageViewer(tk.Tk):

import glob
import tkinter as tki
from PIL import Image, ImageTk


class ImageViewer(tki.Tk):
    def __init__(self):
        """Create the ImageViewer."""
        # Attributes for the image handling.
        self.image_names=glob.glob('/home/pi/Images/*.png')
        self.index = 0
        self.photo = None
        #Button init
        btn= tki.Button(self.root,text="NextPic",command=self.show_image)
        btn.grid(sticky = tki.S)
        # We'll use a Label to display the images.

        self.label = tk.Label(self)
        self.label.pack(padx=5, pady=5)
        # Delay should be in ms.
        self.delay = 1000*2.5
        # Display the first image.
        self.show_image()

    def show_image(self):
        """Display an image."""
        # We need to use PIL.Image to open png files, since
        # tkinter's PhotoImage only reads gif and pgm/ppm files.
        image = Image.open(self.image_names[index])
        # We need to keep a reference to the image!
        self.photo = ImageTk.PhotoImage(image)
        self.index += 1
        if self.index == len(self.image_names):
            self.index = 0
        # Set the image
        self.label['image'] = self.photo
        # Tell tkinter we want this method to be called again after a delay.
        self.after(self.delay, show_image)

root = ImageViewer()
root.mainloop()

这是错误:

   File "slideshow.py", line 41, in <module>
        root = ImageViewer()
      File "slideshow.py", line 19, in __init__
        btn= tki.Button(self.root, text="Next Pic", command=self.show_image)
      File "/usr/lib/python3.5/tkinter/__init__.py", line 1961, in __getattr__
        return getattr(self.tk, attr)
      File "/usr/lib/python3.5/tkinter/__init__.py", line 1961, in __getattr__
        return getattr(self.tk, attr)
      File "/usr/lib/python3.5/tkinter/__init__.py", line 1961, in __getattr__
        return getattr(self.tk, attr)
RecursionError: maximum recursion depth exceeded

递归错误之前的部分被打印了很多次,所以我把它缩短了。

1 个答案:

答案 0 :(得分:2)

导致递归错误的问题是您的ImageViewer类子类Tk,但您从未调用__init__的{​​{1}}方法。这可以防止tkinter成功初始化。

您需要将其添加为Tk中的第一个语句:

ImageViewer.__init__

代码中还有许多其他问题,但它们与您提出的问题无关。