1

I am trying to add a background to a tkinter app. For some reason, when I use class inheritance, I can't make it work:

import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        C = tk.Canvas(self, bg="blue", height=0, width=0)
        filename = tk.PhotoImage(file='bg.png')
        background_label = tk.Label(self, image=filename)
        background_label.place(x=0, y=0, relwidth=1, relheight=1)
        C.pack()

        self.geometry('400x200')

app = App()
app.mainloop()

But if I do this:

import tkinter as tk
top = tk.Tk()
C = tk.Canvas(top, bg="blue", height=0, width=0)
filename = tk.PhotoImage(file='bg.png')
background_label = tk.Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()

top.geometry('200x200')
top.mainloop()

It works perfectly fine. Any idea what I'm missing?

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
Steven G
  • 16,244
  • 8
  • 53
  • 77
  • 5
    You are not [keeping the reference](http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm) of the image hence it gets garbage collected. Gonna add a dupe link in a minute. – Lafexlos Jul 24 '17 at 17:28
  • [Putting gif image in a canvas with Tkinter](https://stackoverflow.com/questions/16424091/putting-gif-image-in-a-canvas-with-tkinter) Can you please try this one? – Lafexlos Jul 24 '17 at 17:30
  • @Lafexlos yes adding self.filename works. thanks for pointing that out! – Steven G Jul 24 '17 at 17:32
  • 3
    `filename` is a horrible name for a variable that holds the *image itself*... – jasonharper Jul 24 '17 at 17:54

0 Answers0