簡體   English   中英

如何在運行時加載圖像tkinter?

[英]how to load image tkinter at runtime?

我正在嘗試瀏覽圖像文件並使用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()

首先,您沒有在方法中保留圖像的引用,這可能會導致圖像完全不顯示。

關於調整大小,可以使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM