Search code examples
pythontkinterbackground-image

Can't seem to add background image in tkinter


I can't seem to add a background image to my code. I've tried pretty much every solution out there for adding a background to a tkinter program but still can't get it to work. The best solution I've tried is the code below, which rather than giving weird errors, just simply doesn't work. Any help would be extremely appreciated as I've been working on this for hours with no avail.

class App:
    def __init__(self, root):

        #setting title
        root.title("undefined")
        #setting window size
        width=1500
        height=900
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        bg = PhotoImage(file="background.png")
        bgimg_label=tk.Label(root, image=bg)
        bgimg_label["anchor"] = "nw"
        bgimg_label.place(x=0,y=0,relwidth=1,relheight=1)

Solution

  • Create image outside the class.

    from tkinter import PhotoImage
    import tkinter as tk
    
    
    class App:
        def __init__(self, root):
            # setting title
            root.title("undefined")
            # setting window size
            width = 1500
            height = 900
            screenwidth = root.winfo_screenwidth()
            screenheight = root.winfo_screenheight()
            alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
            root.geometry(alignstr)
            root.resizable(width=False, height=False)
    
            bgimg_label = tk.Label(root, image=bg)
            bgimg_label["anchor"] = "nw"
            bgimg_label.place(x=0, y=0, relwidth=1, relheight=1)
    
    
    master = tk.Tk()
    bg = PhotoImage(file='background.png')
    App(master)
    master.mainloop()