0

People of the Internet! I'm pretty new to TKinter GUI development, so a lot of the processes happening below are something I've just learned today. The background image (bg.jpg) is not being displayed, although the buttons and other widgets I've tried adding are. Any help? Thanks in advance.

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

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        img = ImageTk.PhotoImage(Image.open("bg.jpg"))

        Width = img.width() // 2
        Height = img.height() // 2

        parent.geometry("{}x{}".format(Width, Height))
        parent.minsize(Width, Height)          # minsize
        parent.maxsize(Width * 2, Height * 2)  # maxsize

        canv = tk.Canvas(parent, width=img.width() * 1.5, height=img.width() * 1.5, bg='white')
        canv.grid(row=0, column=0)
        canv.create_image(0, 0, anchor=tk.NW, image=img)

        class quitButton(tk.Button):
            def __init__(self, parent):
                tk.Button.__init__(self, parent)
                self['text'] = 'exit'
                self['command'] = parent.destroy
                self['bg'] = '#ff4444'
                self.place(relx=0.9, rely=0.9, anchor=tk.CENTER)
        quitButton(parent)

        randomButton = tk.Button(parent, text="text1", bg='#63d8c7')
        randomButton.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root)
    root.mainloop()
peki
  • 669
  • 7
  • 24
  • Possible duplicate of [Python Tkinter 2.7 Issue with image. \[duplicate\]](https://stackoverflow.com/q/27430648/953482) – Kevin Feb 26 '19 at 20:01
  • 3
    It is because you use local variable `img` to hold the image which will be destroyed once exiting the init function. Change `img` to `self.img`. – acw1668 Feb 26 '19 at 23:28
  • thanks a bunch, acw1668 – peki Feb 27 '19 at 10:13

0 Answers0