-2

I started coding recently and decided to start with python. I want to make a program that loads an image from a file open dialog, and then shows that image in my root(). That works, but when I put the loading part in a function it shows the space where the image should be, but no image. My code is:

from tkinter import *
from tkinter import filedialog
from shutil import copyfile
from PIL import ImageTk, Image
import numpy as np
import cv2

root = Tk()
#root.withdraw()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

def odaberiSliku():
    root.filename =  filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
    img = (root.filename)
    copyfile(img,"test.jpg")
    #root.deiconify()
    photo = ImageTk.PhotoImage(Image.open("test.jpg"))
    label = Label(bottomFrame, image=photo)
    label.pack()
    return

button_load = Button(topFrame, text="Odaberi sliku", command=odaberiSliku)
button_load.pack()

root.mainloop()

I get a window like this:

My window

Thank you.

DYZ
  • 55,249
  • 10
  • 64
  • 93
Olat
  • 1
  • 1

1 Answers1

0

Since photo is a local variable in your function, any object associated with it (in your case, the image) is destroyed upon return. In other words, after the function returns, there is no more image to display. Solution: make the variable global.

def odaberiSliku():
    global photo
    # Your code follows
DYZ
  • 55,249
  • 10
  • 64
  • 93
  • 2
    This is a great answer, thank you very much! One more solution I have found just a few moments ago: The solution is to make sure to keep a reference to the Tkinter object, for example by attaching it to a widget attribute. http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm – Olat Jul 04 '18 at 18:29
  • Either way. Just make sure the reference to the image is not destroyed. – DYZ Jul 04 '18 at 18:33