Home > database >  Why Is My Image Not Recognized In Python?
Why Is My Image Not Recognized In Python?

Time:11-09

So I Was Writing This:

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 Strange 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

    .vscode

    Android_Studio

    C   (Nothing To Do With Error)

    HTML (Nothing To Do With Error)

    Java (Nothing To Do With Error)

    JavaScript (Nothing To Do With Error)

    JSON (Nothing To Do With Error)

    Python

        CodeHook

            BGnew.png

            icon.png

            main.py (file in which error occured)


    Visual Studio

Python Version: 3.9.7 IDE: Visual Studio Code (User)

CodePudding user response:

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.

  • Related