如何在python tkinter中显示已调整大小的图像

问题描述:

我正在使用Tkinter开发一个使用Tkinter学习图像处理的GUI。 GUI的流程将作为如何在python tkinter中显示已调整大小的图像

加载图像(jpg | PNG | ...)=>调整大小/缩略图(240 * 240)=>预览图像

from Tkinter import * 
import PIL 
class Window:  
    def __init__(self, master): 
     master.title("Image Processing test") 
     master.minsize(800, 400) 

     from PIL import Image 
     im = Image.open("IMG_0562.png") 
     size = 240, 240 
     im.thumbnail(size) 
     p = im.tobytes() 

     # photo = PhotoImage(file="IMG_0562.gif") 
     # photo = BitmapImage(data=p) 
     w = Label(root, image=photo, width=240, height=240).grid(row=20, column=2) 
     self.photo = photo 


root = Tk() 

window = Window(root) 

root.mainloop() 

我的问题是我不能以适当的格式获取图像以在Label中使用它。由于Label只接受PhotoImageBitmapImagePhotoImage不支持pngjpg文件。所以我使用PILImage加载和调整我的彩色图像。我试过Image.tobitmap()Image.tobytes(),但在这种情况下没有用。

通过使用保存在存储器中的图像问题解决了io.BytesIO()

from Tkinter import * 
from PIL import Image 
import io 

class Window:  
    def __init__(self, master): 
     master.title("Image Processing test") 
     master.minsize(800, 400) 

     im = Image.open("IMG_0562.png") 
     size = 240, 240 
     im.thumbnail(size) 
     b = io.BytesIO() 
     im.save(b, 'gif') 
     p = b.getvalue() 
     photo = BitmapImage(data=p) 
     w = Label(root, image=photo, width=240, height=240).grid(row=20, column=2) 
     self.photo = photo 

root = Tk()  
window = Window(root) 
root.mainloop()