我想编写一个幻灯片,在按下按钮后更改图像。我还希望能够双向更改图像。
显然,我找到了一些代码,有些符合我的要求,但并不完全符合我的要求。 类 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
Recursion Error 之前的部分打印了很多次,所以我把它剪短了。
请您参考如下方法:
导致递归错误的问题是你的ImageViewer类子类Tk,但是你从来没有调用Tk的。这会阻止 tkinter 成功初始化。__init__方法
您需要将此添加为 ImageViewer.__init__ 中的第一条语句:
super().__init__()
代码中还有许多其他问题,但它们与您提出的问题无关。
