0

***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.

JacksonPro
  • 3,135
  • 2
  • 6
  • 29
Google
  • 1
  • Well. Your error message is pretty straightforward. Python does not have a permission to open your file. – Aleksander Krauze Dec 13 '20 at 16:37
  • 1
    The path is a directory so it cannot be open. You need to provide a path of image file. But event you provide a correct path to a image, it will not be shown because it will be garbage collected and you did not call any layout function on `label` as well. Also `x.mainloop()` is also missing. – acw1668 Dec 13 '20 at 16:38

2 Answers2

0

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

Seintian
  • 151
  • 1
  • 1
  • 11
0

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()
acw1668
  • 40,144
  • 5
  • 22
  • 34