【问题标题】:File Not Found Error for displaying images using Tkinter使用 Tkinter 显示图像时未找到文件错误
【发布时间】:2020-02-18 11:41:12
【问题描述】:

所以我有一个文件列表并选择了一个随机文件,然后应该显示图像。

我目前的代码如下:

    def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(question))
        img.place(x=100, y=100)

我在实施时单独检查了每个部分,并且所有正确的文件都放入了一个列表中,因为我希望它们也可以在我想要的时候选择一个随机文件,但问题是我每次都会收到一条错误消息我运行它说:

 File "C:\Users\cj_he\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2809, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Particle Q3.png'

我不明白,因为我可以进入我的文件,我可以看到文件在那里,我可以打开它,但由于某种原因 python 找不到该文件。我正在使用 PyCharm IDE。有什么建议吗?

【问题讨论】:

  • 在列出您提供路径时。但是在读取文件时,您只传递了文件名。打开文件时需要在文件名前附加路径。
  • 检查您当前的工作目录使用:print(os.getcwd())。与图像的位置进行比较。
  • 使用Image.open(path.join(examQ_dir, filename))
  • "img.place(":这会失败,你不能放置图片。阅读Why does Tkinter image not show up if created in a function?

标签: python image file tkinter pycharm


【解决方案1】:

在列出时,您正在给出一条路径。但是在读取文件时,您只传递了文件名。打开文件时需要在文件名前附加路径。

试试这个:

import os

def DisplayQ(self):
        dir = path.dirname(__file__)
        examQ_dir = path.join(dir, 'Exam Questions')
        questions = os.listdir(examQ_dir)  # put the files into a list
        question = random.choice(questions)
        img = ImageTk.PhotoImage(Image.open(os.path.join(examQ_dir, question)))

【讨论】:

  • @PrashantKumar 谢谢这解决了查找文件的问题。
  • @stovfl 感谢我关注的链接,现在显示图像。我没有意识到这是一个问题,因为在这个问题中没有任何工作,但用一块石头杀死了 2 只鸟,所以谢谢 :)
  • @stovfl,改变了它。夏洛特,太好了,我们能帮上忙。如果它有助于解决您的问题,请将答案标记为已接受。并感谢 stovfl 指出代码中的另一个问题。干杯:D
猜你喜欢
  • 2013-03-21
  • 2020-11-04
  • 1970-01-01
  • 2021-06-02
  • 2021-05-11
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
  • 2020-10-11
相关资源
最近更新 更多