I was creating a image with PhotoImage and this error happened

931 views Asked by At

***Error message :

Traceback (most recent call last):
  File "C:/Users/gurse/Desktop/Khanda/Khanda.py", line 3, in <module>
    label = Label(x, image=PhotoImage(file=r"C:\Users\gurse\Desktop\Khanda"))
  File "C:\Users\gurse\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 4062, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\gurse\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 4007, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "C:\Users\gurse\Desktop\Khanda": permission denied *****

My current code :

 from tkinter import *
 x = Tk()
 label = Label(x, image=PhotoImage(file=r"C:\Users\gurse\Desktop\Khanda"))

And the backslashes turn into a Y with 2 lines across it.

2

There are 2 answers

0
Seintian On

That error says that it can't reach the image.

In this case, you have put only the path of the image, but the image name isn't included in it.

To resolve, you have to put also the name of the image in the path like:

r"C:\Users\gurse\Desktop\Khanda\TestImage.png

A small advice -> PhotoImage takes only a few extensions for images (ie. jpeg will occur an error)

I hope that I've been clear ;)

EDIT: The user acw1668 isn't wrong: you have to use the method mainloop() to show the window with the widgets

0
acw1668 On

According to the information in the traceback, "C:\Users\gurse\Desktop\Khanda" is a directory. So trying to open a directory as a file will raise the exception.

So you need to pass a path of an image file instead, like "C:\Users\gurse\Desktop\Khanda\sample.png".

However since you pass the result of PhotoImage(...) to image option directly, the image will be garbage collected because there is no variable references it. So you need to use a variable to store the result of PhotoImage(...).

Also you need to call grid() or pack() or place() on the label otherwise it won't show up.

Finally you need to call x.mainloop() otherwise the program will exit immediately.

Below is an example code based on yours:

from tkinter import *
x = Tk()
image = PhotoImage(file="C:/Users/gurse/Desktop/sample.png")
label = Label(x, image=image)
label.pack()
x.mainloop()