【问题标题】:Tkinter & PIL Resize an image to fit a labelTkinter & PIL 调整图像大小以适合标签
【发布时间】:2013-06-25 10:46:20
【问题描述】:

我正在尝试使用 PIL 在 Tkinter 中显示图片。正如上一个问题中所建议的,我为此使用了一个标签:

from Tkinter import *

class App(Frame):
    def __init__(self,master):
        Frame.__init__(self,master)
        self.grid(row=0)
        self.columnconfigure(0,weight=1)
        self.rowconfigure(0,weight=1)
        image = Image.load('example.png')
        image = ImageTk.PhotoImage(image.convert('RGBA'))
        self.display = Label(self,image=image)
        self.display.grid(row=0)

root = Tk()
app = App(root)
app.mainloop()
root.destroy()

有没有办法调整图像大小以适合标签?例如,如果exam​​ple.png是2000x1000,但窗口只有800x600,则只显示图像的一部分。

【问题讨论】:

    标签: python tkinter python-imaging-library


    【解决方案1】:

    如果你知道你想要的大小,使用 PIL 来调整图像大小:

    class App(Frame):
        def __init__(self, master):
            Frame.__init__(self, master)
            self.grid(row=0)
            self.columnconfigure(0,weight=1)
            self.rowconfigure(0,weight=1)
            self.original = Image.open('example.png')
            resized = self.original.resize((800, 600),Image.ANTIALIAS)
            self.image = ImageTk.PhotoImage(resized) # Keep a reference, prevent GC
            self.display = Label(self, image = self.image)
            self.display.grid(row=0)
    

    你也可以使用 Canvas 来显示图像,我更喜欢它:

    from Tkinter import *
    from PIL import Image, ImageTk
    
    class App(Frame):
        def __init__(self, master):
            Frame.__init__(self, master)
            self.columnconfigure(0,weight=1)
            self.rowconfigure(0,weight=1)
            self.original = Image.open('example.png')
            self.image = ImageTk.PhotoImage(self.original)
            self.display = Canvas(self, bd=0, highlightthickness=0)
            self.display.create_image(0, 0, image=self.image, anchor=NW, tags="IMG")
            self.display.grid(row=0, sticky=W+E+N+S)
            self.pack(fill=BOTH, expand=1)
            self.bind("<Configure>", self.resize)
    
        def resize(self, event):
            size = (event.width, event.height)
            resized = self.original.resize(size,Image.ANTIALIAS)
            self.image = ImageTk.PhotoImage(resized)
            self.display.delete("IMG")
            self.display.create_image(0, 0, image=self.image, anchor=NW, tags="IMG")
    
    root = Tk()
    app = App(root)
    app.mainloop()
    root.destroy()
    

    【讨论】:

    • 抱歉回复慢,我不在。有什么办法可以查出标签本身的大小?
    • @DoctorSelar Label.winfo_height(), Label.winfo_width() 如果我没记错的话。您必须先致电Label.update()
    猜你喜欢
    • 2015-07-02
    • 1970-01-01
    • 2012-12-01
    • 2015-10-07
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多