2013-06-27 62 views
4

我試圖在使用PIL的Tkinter中顯示圖片。正如前面的問題所建議的,我爲此使用標籤:Tkinter&PIL調整圖像以適應標籤

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() 

有沒有辦法調整圖像的大小以適應標籤?例如,如果exam​​ple.png爲2000x1000,但窗口只有800x600,則只顯示圖像的一部分。

回答

9

如果你知道你想要的大小,使用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) 

你也可以使用一個畫布上顯示的圖像,我喜歡它更多:

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() 
+0

對不起回覆緩慢,我不在。有沒有辦法找出標籤本身的大小? – DoctorSelar