Search code examples
pythonpython-3.xtkinterbackground-image

How can I put an image as a background on tkinter?


To change things up, I wanted to put blue wallpaper image as my background on my python script. Here is the code:

from tkinter import *

root = Tk()
root.title("")
root.iconbitmap()
#root.minsize(width=1370, height=800)
#root.maxsize(width=1370, height=800)

background = PhotoImage(file="background.jpeg")
background_label = Label(root,image=background)
background_label.place(x=0,y=0,relwidth=1,relheight=1)

root.mainloop()

However, when I run this code this error pops up:

File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 4061, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 4006, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "background.jpeg"

Does anyone know how to solve this problem?


Solution

  • You Can Use ImageTk:

    from PIL import ImageTk
    from tkinter import *
    
    root = Tk()
    root.title("")
    root.iconbitmap()
    
    background = ImageTk.PhotoImage(file="background.jpeg")
    background_label = Label(root,image=background)
    background_label.place(x=0,y=0,relwidth=1,relheight=1)
    
    root.mainloop()
    

    Hope It Helps :D