【发布时间】: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