在Tkinter中使用PIL调整图片大小
我现在正在用PIL这个库在Tkinter中显示图片。我想临时调整这些图片的大小,这样看起来会更方便。请问我该怎么做呢?
代码片段:
self.pw.pic = ImageTk.PhotoImage(Image.open(self.pic_file))
self.pw.pic_label = TK.Label(self.pw , image=self.pw.pic,borderwidth=0)
self.pw.pic_label.grid(column=0,row=0)
3 个回答
3
最简单的方法可能是基于原始图像创建一个新图像,然后用这个更大的副本替换掉原来的图像。为了做到这一点,tk图像有一个叫做copy
的方法,这个方法可以在制作副本时对原始图像进行放大或缩小。不过,遗憾的是,它只能以2的倍数进行放大或缩小。
7
如果你不想保存它,可以试试这个:
from Tkinter import *
from PIL import Image, ImageTk
root = Tk()
same = True
#n can't be zero, recommend 0.25-4
n=2
path = "../img/Stalin.jpeg"
image = Image.open(path)
[imageSizeWidth, imageSizeHeight] = image.size
newImageSizeWidth = int(imageSizeWidth*n)
if same:
newImageSizeHeight = int(imageSizeHeight*n)
else:
newImageSizeHeight = int(imageSizeHeight/n)
image = image.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
img = ImageTk.PhotoImage(image)
Canvas1 = Canvas(root)
Canvas1.create_image(newImageSizeWidth/2,newImageSizeHeight/2,image = img)
Canvas1.config(bg="blue",width = newImageSizeWidth, height = newImageSizeHeight)
Canvas1.pack(side=LEFT,expand=True,fill=BOTH)
root.mainloop()
46
这是我做的事情,效果还不错...
image = Image.open(Image_Location)
image = image.resize((250, 250), Image.ANTIALIAS) ## The (250, 250) is (height, width)
self.pw.pic = ImageTk.PhotoImage(image)
就这样 :)
补充说明:
这是我的导入语句:
from Tkinter import *
import tkFont
from PIL import Image
这是我根据这个例子改编的完整工作代码:
im_temp = Image.open(Image_Location)
im_temp = im_temp.resize((250, 250), Image.ANTIALIAS)
im_temp.save("ArtWrk.ppm", "ppm") ## The only reason I included this was to convert
## The image into a format that Tkinter woulden't complain about
self.photo = PhotoImage(file="ArtWrk.ppm") ## Open the image as a tkinter.PhotoImage class()
self.Artwork.destroy() ## Erase the last drawn picture (in the program the picture I used was changing)
self.Artwork = Label(self.frame, image=self.photo) ## Sets the image too the label
self.Artwork.photo = self.photo ## Make the image actually display (If I don't include this it won't display an image)
self.Artwork.pack() ## Repack the image
这里是PhotoImage类的文档: http://www.pythonware.com/library/tkinter/introduction/photoimage.htm
注意... 在查看了pythonware关于ImageTK的PhotoImage类的文档后(内容很少),我发现如果你的代码片段能正常工作,那么只要你导入了PIL的“Image”库和PIL的“ImageTK”库,并且这两个库和tkinter都是最新的,那么这个也应该能正常工作。另外,我甚至找不到“ImageTK”模块的相关信息。你能把你的导入语句发一下吗?