-1

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)

1 Answers1

0

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()
Aram SEMO
  • 146
  • 8
  • While this code might answer the question, it would be better to include some context, explaining _how_ it works and _when_ to use it. Code-only answers are not useful in the long run. – martineau Jan 31 '22 at 08:11