Python Tkinter & PIL 调整图像大小以适合标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17351524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tkinter & PIL Resize an image to fit a label
提问by DoctorSelar
I'm trying to show a picture in Tkinter using PIL. As suggested in a previous question, I use a label for this:
我正在尝试使用 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()
Is there a way to resize the image to fit the label? For instance, if example.png is 2000x1000 but the window is only 800x600, only a part of the image is displayed.
有没有办法调整图像大小以适合标签?例如,如果 example.png 是 2000x1000 但窗口只有 800x600,则只显示图像的一部分。
回答by Txema
If you know the size you want, use PIL to resize the image:
如果您知道所需的大小,请使用 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)
You could also use a Canvas to display the image, I like it more:
您也可以使用 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()