【问题标题】:I was creating a image with PhotoImage and this error happened我正在使用 PhotoImage 创建图像,并且发生了此错误
【发布时间】:2020-12-13 15:29:33
【问题描述】:

***错误信息:

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

我当前的代码:

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

反斜杠变成了一个 Y,有 2 行。

【问题讨论】:

  • 好吧。您的错误消息非常简单。 Python 无权打开您的文件。
  • 路径为目录,无法打开。您需要提供图像文件的路径。但是,如果您提供了正确的图像路径,它将不会显示,因为它将被垃圾收集,并且您也没有在 label 上调用任何布局函数。 x.mainloop() 也不见了。

标签: python tkinter photoimage


【解决方案1】:

该错误表明它无法访问图像。

在这种情况下,您只输入了图像的路径,但图像名称未包含在其中。

要解决这个问题,您还必须将图像的名称放在路径中,例如:

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

一个小建议 -> PhotoImage 只需要对图像进行一些扩展(即 jpeg 会出现错误)

我希望我已经清楚了;)

编辑: 用户 acw1668 没有错:您必须使用方法 mainloop() 来显示带有小部件的窗口

【讨论】:

    【解决方案2】:

    根据traceback中的信息,"C:\Users\gurse\Desktop\Khanda"是一个目录。所以尝试将目录作为文件打开会引发异常。

    所以你需要传递一个图像文件的路径,比如"C:\Users\gurse\Desktop\Khanda\sample.png"

    但是,由于您将PhotoImage(...) 的结果直接传递给image 选项,因此图像将被垃圾收集,因为没有变量引用它。所以你需要使用一个变量来存储PhotoImage(...)的结果。

    您还需要在标签上调用grid()pack()place(),否则它不会显示。

    最后你需要调用x.mainloop()否则程序会立即退出。

    以下是基于您的示例代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多