0

I am trying to make tkinter UI that changes the image by control: loading folder/file, initiate, etc.

My code is at below and it does not load any image.

window = tk.Tk()

class window_tk():
    def __init__(self,main):
        self.canvas = tk.Canvas(main, bg='white' )
        self.init_img_route = "C:/Users/ISDL_gram/Documents/hpe/3.png"
        self.img = itk.PhotoImage(file=self.init_img_route)
        self.bg= self.canvas.create_image(0,0,anchor = tk.NW,image=self.img)
        width = self.img.width()
        height = self.img.height()
        main.geometry(str(width+100)+'x'+str(height+100))
        self.canvas.pack(fill='both',expand=1)


window_tk(window)
window.mainloop()

Since I succeeded loading img when I made my code function-based, and I referred How to update an image on a Canvas? and decided to make it using class, which does not work. What did I miss? I have no clue.


I editted the code slightly, only showing codes for images.

EJ Song
  • 123
  • 2
  • 13

1 Answers1

3

It is because you did not use a variable to store the reference of window_tk class, so it is garbage collected. Save a reference:

window = tk.Tk()

class window_tk():
    def __init__(self,main):
        self.canvas = tk.Canvas(main, bg='white' )
        self.init_img_route = "C:/Users/ISDL_gram/Documents/hpe/3.png"
        self.img = itk.PhotoImage(file=self.init_img_route)
        self.bg= self.canvas.create_image(0,0,anchor = tk.NW,image=self.img)
        width = self.img.width()
        height = self.img.height()
        main.geometry(str(width+100)+'x'+str(height+100))
        self.canvas.pack(fill='both',expand=1)


app = window_tk(window) # save a reference
window.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34