2017-08-04 1063 views
0

我正在使用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(),但在這種情況下沒有用。

回答

0

通過使用保存在存儲器中的圖像問題解決了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() 
相關問題