我试图用Tkinter制作幻灯片,但我在调整图像大小时遇到了问题。它们只显示为默认大小,而我希望它们都是统一的。我可以使用Image.open为单个图像执行此操作并调整大小,但我无法理解如何使其在迭代中工作。我很感激帮助:
import Tkinter as tk
from PIL import Image, ImageTk
from itertools import cycle
class App(tk.Tk):
def __init__(self, image_files, x, y, delay):
tk.Tk.__init__(self)
self.geometry('+{}+{}'.format(x,y))
self.delay = delay
self.pictures = cycle((ImageTk.PhotoImage(file=image), image) for image in image_files)
self.pictures = self.pictures
self.picture_display = tk.Label(self)
self.picture_display.pack()
def show_slides(self):
img_object, img_name = next(self.pictures)
self.picture_display.config(image=img_object)
self.title(img_name)
self.after(self.delay, self.show_slides)
def run(self):
self.mainloop()
delay = 3500
image_files = [
'c:/users/xxx/pictures/47487_10100692997065139_1074926086_n.jpg',
'E:\\1415\\20141216_105336.jpg'
]
x = 100
y = 50
app = App(image_files,x,y,delay)
app.show_slides()
app.run()
答案 0 :(得分:3)
你很亲密,但还没到那里。因此,我更改了您的示例以使其工作:
import Tkinter as tk
from PIL import Image, ImageTk
from itertools import cycle
class App(tk.Tk):
def __init__(self, image_files, x, y, delay):
tk.Tk.__init__(self)
self.geometry('+{}+{}'.format(x,y))
self.delay = delay
#self.pictures = cycle((ImageTk.PhotoImage(file=image), image) for image in image_files)
self.pictures = cycle(image for image in image_files)
self.pictures = self.pictures
self.picture_display = tk.Label(self)
self.picture_display.pack()
self.images = [] # to keep references to images.
def show_slides(self):
img_name = next(self.pictures)
image_pil = Image.open(img_name).resize((300, 300)) #<-- resize images here
self.images.append(ImageTk.PhotoImage(image_pil))
self.picture_display.config(image=self.images[-1])
self.title(img_name)
self.after(self.delay, self.show_slides)
def run(self):
self.mainloop()
delay = 3500
image_files = [
'./empty.gif',
'./empty2.gif',
'./empty1.gif'
]
x = 200
y = 150
app = App(image_files,x,y,delay)
app.show_slides()
app.run()
基本上,在创建ImageTk.PhotoImage
的实例之前,必须使用PIL图像完成图像大小调整。在两个关键点我在示例中做了评论,因此您知道在哪里寻找。希望这会有所帮助。