user3201928
user3201928

Reputation: 380

how to load image tkinter at runtime?

I am trying to browse image file and load it in label using tkinter. I am unable to load the new browsed image. I am just trying to show preview of the image in the label right now it is loading full image hence only some part of the image is captured. How can I reduce the image size that is loaded in the label so full image is previewed label. source code:

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

Upvotes: 0

Views: 1058

Answers (1)

Lafexlos
Lafexlos

Reputation: 7735

First you are not keeping a reference for your image in your method, that might lead to that, your image not appear at all.

About resizing, you can use 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)

Upvotes: 1

Related Questions