0

I'm new at tkinter.

I'd like to fill the Label with image. but it doesn't work at OOP structure.

For example,

import os
import cv2
import tkinter as tk

root = tk.Tk()
img = tk.PhotoImage(file='../resource/default.png')
capture = tk.Label(root, text="Class", compound="top", image=img)
capture.pack()
root.mainloop()

above is working, but below is not working.

How can I make it working with class (like below code)?

import os
import cv2
import tkinter as tk

class App(tk.Label):
    def __init__(self, master=None):
        tk.Label.__init__(self, master)
        img = tk.PhotoImage(file='../resource/default.png')
        self.configure(text="Class", compound="top", image=img)
        self.pack()


root = tk.Tk()
App(root)
root.mainloop()
Henry Lee
  • 1
  • 1

1 Answers1

0

(Updated) Per a question linked in the comment, it seems .configure doesn't actually assign a reference to the image, so it's a simple case of the object not existing. Thus we just need to keep a reference to it to stop it being garbage collected---anything (which doesn't collide) will work, but .image is as good as anything else.

import tkinter as tk

class App(tk.Label):
    def __init__(self, master=None):
        tk.Label.__init__(self, master)
        self.img = tk.PhotoImage(file='../resource/default.png')
        self.configure(text="Class", compound="top", image=self.img)
        self.pack()


root = tk.Tk()
App(root)
root.mainloop()

I'm leaving this answer up for the time being, but it seems this question is actually a dupe.

2e0byo
  • 4,321
  • 1
  • 3
  • 22
  • Most of the time, if you don't understand the answer, it isn't going to teach OP what to do to avoid the problem in the future. – TheLizzard Sep 28 '21 at 10:52
  • @TheLizzard that's a fair point and I was being lazy. I should have looked at the source for `.configure` to see that it wasn't keeping a reference; I didn't even *think* it might not be doing so. – 2e0byo Sep 28 '21 at 11:00
  • Simply change local variable `img` to instance variable `self.image` is enough. – acw1668 Sep 28 '21 at 11:11
  • yes that's not so horribly backwards as assigning later. Bother, answering in spare time is *not* working today – 2e0byo Sep 28 '21 at 11:26
  • Thanks for your kindness, but It's not working with your advice & code. I've searched this issue before and got similar answer as yours. I cannot solve the issue and leave this post (question) finally to get the one. – Henry Lee Sep 29 '21 at 23:58
  • @henrylee I suggest you open a new q, with the code on this (or the linked) answer, and what happens when you run it. Keeping an instance around certainly works for me. – 2e0byo Sep 30 '21 at 08:49