【问题标题】:Resizing images with ImageTk.PhotoImage with Tkinter/Python使用 Tkinter/Python 使用 ImageTk.PhotoImage 调整图像大小
【发布时间】:2015-04-12 09:54:56
【问题描述】:

我正在尝试使用 Tkinter 制作幻灯片,但无法调整图像大小。它们仅显示为默认尺寸,而我想让它们全部统一。我可以使用 Image.open 和 resize 对单个图像执行此操作,但我无法弄清楚如何让它在迭代中工作。非常感谢您的帮助:

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()

【问题讨论】:

  • 你试过 myImage.subsample(N,N) 吗?

标签: python tkinter


【解决方案1】:

您已经很接近了,但还没有完全到达那里。因此,我更改了您的示例以使其正常工作:

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 图像调整图像大小。在两个关键点我在例子中做了 cmets,所以你知道在哪里寻找。希望这会有所帮助。

【讨论】:

  • 这比我想出的要简单得多 =)
猜你喜欢
  • 2013-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 2018-05-13
  • 1970-01-01
相关资源
最近更新 更多