2017-07-18 26 views
0

我正在嘗試瀏覽圖像文件並使用tkinter將其加載到標籤中。我無法加載新的瀏覽圖像。我只是試圖顯示標籤中的圖像預覽,現在它正在加載完整的圖像,因此只有圖像的一部分被捕獲。如何縮小標籤中加載的圖像大小,以便預覽全圖像標籤。 源代碼:如何在運行時加載圖像tkinter?

root = Tk() 
def browsefunc(): 
    filename = fd.askopenfilename() 
    print(filename) 
    ss=ImageTk.PhotoImage(Image.open(filename)) 
    panel.configure(image=ss) 

file=r"C:/img.jpg" 
img = ImageTk.PhotoImage(Image.open(file)) 
browsebutton = Button(root, text="Browse", command=browsefunc, justify ="center") 
panel = Label(root,height="500",width="500", image = img,justify="left") 
panel.pack(side = "top", expand = "yes") 

browsebutton.pack(side="bottom") 
root.mainloop() 

回答

1

首先,你不守你的圖像的參考你的方法,即威力導致的是,您的圖像不會出現在所有。

關於調整大小,您可以使用PIL.Image.resize()

def browsefunc(): 
    filename = fd.askopenfilename() 
    print(filename) 
    si = Image.open(filename) 
    h = panel.winfo_height() # label's current height 
    w = panel.winfo_width() # label's current width 
    si = si.resize((h,w)) 
    ss = ImageTk.PhotoImage(si) 
    panel.image=ss # keeping a reference!! 
    panel.configure(image=ss) 
+0

感謝您的解決方案,但我得到錯誤「不能援引‘winfo’命令:應用程序已被破壞」,在你的問題 – user3201928

+0

由於代碼不應該產生這一點。看起來,您的標籤在此時無法到達/銷燬。 – Lafexlos

+0

它最初工作,但當我嘗試使用按鈕單擊文件瀏覽器獲取圖像圖像加載,但應用調整大小拋出錯誤「未知的重採樣過濾器」我用調整大小(500,500) – user3201928