'Why Is My Image Not Recognized In Python?
I wrote this code:
from tkinter import *
from locate import this_dir
path = str(this_dir())
print(path + "\\BGnew.png")
window = Tk()
window.geometry("480x480")
window.title("CodeHook - Start Menu")
ico = PhotoImage(file = path + "\\icon.png")
bg = PhotoImage(file = path + "\\BGnew.png")
window.iconphoto(True, ico)
c=Canvas(window,bg="gray16",height=200,width=200)
filename=PhotoImage(file= bg)
background_label=Label(window,image=filename)
background_label.place(x=0,y=0,relwidth=1,relheight=1)
new_workspace = Button(window, text = "New Workspace", font = ("", 13))
new_workspace.pack()
window.mainloop()
When An Error Occured:
Traceback (most recent call last): File "c:\Users\Dani\Desktop\Code\Python\CodeHook\main.py", line 17, in filename=PhotoImage(file= bg) File "C:\Users\Dani\AppData\Local\Programs\Python\Python39\lib\tkinter_init_.py", line 4064, in init Image.init(self, 'photo', name, cnf, master, **kw) File "C:\Users\Dani\AppData\Local\Programs\Python\Python39\lib\tkinter_init_.py", line 4009, in init self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "pyimage2": no such file or directory
Here Is My Folder Structure:
Code
Python
CodeHook
BGnew.png
icon.png
main.py (file in which error occured)
Python Version: 3.9.7 IDE: Visual Studio Code (User)
Solution 1:[1]
You already have a PhotoImage
object in bg variable.
So you can remove line filename=PhotoImage(file= bg)
and modify background_label=Label(window,image=filename)
to background_label=Label(window,image=bg)
.
Small addition: you can use os.getcwd()
to get current directory. Also it is a bad practice to concatenate path and filename, you can use os.path.join()
to do that.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | balrundev |