本文介绍了Tkinter& PIL调整图像大小以适合标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用PIL在Tkinter中显示图片.如上一个问题所建议,我为此使用了一个标签:
I'm trying to show a picture in Tkinter using PIL. As suggested in a previous question, I use a label for this:
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()
是否可以调整图像大小以适合标签?例如,如果example.png为2000x1000,但窗口仅为800x600,则仅显示图像的一部分.
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.
推荐答案
如果知道所需大小,请使用PIL调整图像大小:
If you know the size you want, use PIL to resize the image:
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显示图像,我更喜欢它:
You could also use a Canvas to display the image, I like it more:
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()
这篇关于Tkinter& PIL调整图像大小以适合标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!