简体   繁体   English

文件未找到,文件不存在(jpg)

[英]file not found, file doesn't exist (jpg)

File not found, no such file or directory 找不到文件,没有这样的文件或目录

from tkinter import *
from PIL import Image, ImageTk
import os
import sys

root = Tk() # Create the root (base) window 
root.title("tkinter experiment")
root.iconbitmap("knuckes_-_Copy.ico")

canvas = Canvas(root, width=210, height=210, background="bisque")
canvas.pack(side="bottom", fill="both", expand=True)

img = open("knuckles.jpg", "r")
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")

root.mainloop()

I'd expect the file "knuckles.jpg" to be stored in the img variable for later use in a window, instead, the terminal returns that the file doesn't exist even though its in the same directory as the .py file. 我希望文件“knuckles.jpg”存储在img变量中以供以后在窗口中使用,而终端返回该文件不存在,即使它与.py文件位于同一目录中。

error log: 错误日志:

Traceback (most recent call last):
  File "Image.py", line 14, in <module>
    img = open("knuckles.jpg", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'knuckles.jpg'

也许完整路径而不仅仅是文件名将解决您的问题。

It seems in this code. 看来在这段代码中。 you are not using Image and ImageTk or you referred a wrong example. 你没有使用Image和ImageTk,或者你引用了一个错误的例子。

img = open("knuckles.jpg", "r")

Correct code line should be 应该是正确的代码行

img = ImageTk.PhotoImage(Image.open("knuckles.jpg","r"))  

You can try to change and execute. 您可以尝试更改和执行。 I just tried and it is working. 我刚试过,它正在工作。

It doesn't matter if it's in the same file as the .py file -- that's not where python looks for files. 它与.py文件在同一个文件中并不重要 - 这不是python查找文件的地方。 It looks for files in your current working directory, which may be different than the location of the script. 它会查找当前工作目录中的文件,这些文件可能与脚本的位置不同。

If you want to look in the same folder as the script, you need to compute that with something like this: 如果要查看与脚本相同的文件夹,则需要使用以下内容进行计算:

import os.path
...
script_dir = os.path.dirname(__file__)
image_file = os.path.join(script_dir, "knuckles.jpg")

You have other problems in your code, such as tkinter not supporting .jpg files and the img parameter not taking an open file handle, but the above answers the "file not found" issue which is what you were asking about. 您的代码中还有其他问题,例如tkinter不支持.jpg文件和img参数没有打开文件句柄,但上面回答了“找不到文件”问题,这就是您所询问的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM