-1

I'm trying to get the background of my TKinter app to be a picture. The code works absolutely fine before I put it into its method and class.

import tkinter as tk
from tkinter import *
from PIL import ImageTk,Image

class simpleapp_tk(tk.Tk):
    def __init__(self,parent):
        tk.Tk.__init__(self,parent)
        self.parent = parent  #makes self.parent the parent
        self.Background()


    def Background(self):
        canvas = Canvas(self, width = 0, height = 0)
        canvas.pack(expand = YES, fill = BOTH)
        img = Image.open("watercoffee.jpg")
        photo = ImageTk.PhotoImage(img)
        canvas.create_image(0, 0, anchor=NW, image = photo)

if __name__ == "__main__":   #runs code
    app = simpleapp_tk(None)
    app.wm_geometry("625x390") # window size fed into app
    app.title('My Application')
    app.mainloop()

What am I missing?

trincot
  • 317,000
  • 35
  • 244
  • 286
Steph
  • 11
  • 2
  • Why do you think it's not working? Is the program crashing? Is it showing the wrong image? The correct image in the wrong place? No image? ...? – Bryan Oakley Jan 19 '19 at 22:58
  • Your `parent` handling is useless. `tk.Tk` **is** the `root` and have **no** parent. Remove all `parent` code lines. Your image get probably **garbage collected**, read [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/a/16424553/7414759) – stovfl Jan 20 '19 at 10:57

1 Answers1

0

See my comments indicated by ## in the amended code below.

import tkinter as tk
#from tkinter import * ## Why r u importing tkinter twice? Redundant.
from PIL import ImageTk,Image

class simpleapp_tk(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        #self.parent = parent  #makes self.parent the parent ## Tk is the top most widget, it does not have a parent/master
        self.Background()


    def Background(self):
        self.canvas = tk.Canvas(self, width=0, height=0) #Why use width=0 & height=0? Redundant.
        self.canvas.pack(expand='yes', fill='both')
        img = Image.open("watercoffee.jpg")
        self.photo = ImageTk.PhotoImage(img) ##images needs to be an attribute in a class. See 2nd comment in your question for explanation. 
        self.canvas.create_image(0, 0, anchor='nw', image=self.photo)  ##use self.photo

if __name__ == "__main__":   #runs code
    app = simpleapp_tk() ##removed None
    app.wm_geometry("625x390") # window size fed into app
    app.title('My Application')
    app.mainloop()
Sun Bear
  • 7,594
  • 11
  • 56
  • 102
  • thankyou i really appreciate it, and like i said im really new to this. ill take all of this into account to further my code – Steph Jan 27 '19 at 19:48