找不到文件,使用Tkinter显示图像时出错

问题描述 投票:-1回答:1

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

到目前为止,我的代码如下:

    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。关于这个问题有什么建议吗?

python image file tkinter pycharm
1个回答
0
投票

同时列出您正在提供的路径。但是,在读取文件时,您仅传递文件名。在打开文件期间,您需要在文件名之前附加路径。

尝试一下:

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

© www.soinside.com 2019 - 2024. All rights reserved.