【问题标题】:"IOError No such file or directory" for an image file that IS in the current directory当前目录中的图像文件的“IOError No such file or directory”
【发布时间】:2011-10-30 05:04:32
【问题描述】:

我正在使用 Python Imaging Library 和 Tkinter。 我目前正在尝试将图像显示为标签,并且出现上述异常。 我的35行源码:

from PIL import Image, ImageTk
from Tkinter import Tk, Frame, Label

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Label")

        self.img = Image.open("diesl.jpg")
        diesl = ImageTk.PhotoImage(self.img)
        label = Label(self, image=diesl)

        label.image = diesl
        label.pack()

        self.pack()

    def setGeometry(self):
        w, h = self.img.size
        self.parent.geometry(("%dx%d+300+300") % (w, h))

def main():
    root = Tk()
    ex = Example(root)
    ex.setGeometry()
    root.mainloop()

if __name__ == '__main__':
    main()

【问题讨论】:

  • 你怎么知道它实际上是在当前目录中,而不是在你只认为是当前目录的其他目录中?
  • 试试这个代码:f=open("diesl.jpg") 如果它不起作用,那就是权限问题。
  • @lc2817:权限赋予不同的IOError 值。
  • 好的,在这种情况下你是对的,他没有将文件放在同一目录中。
  • 我已经三重检查了。我肯定在同一个目录下。

标签: python tkinter notepad++ python-imaging-library python-2.7


【解决方案1】:

实际上,您的评论是正确的:Notepad++ 似乎从其自己的目录启动文件。

如果您仍打算使用记事本++,您可以在此处找到问题的解决方案:http://damienlearnsperl.blogspot.com/2009/01/launch-your-perl-script-from-notepad.html(查看 Lee 的评论)

【讨论】:

  • 我没有意识到 npp 使用自己的目录作为工作目录。非常感谢!
【解决方案2】:

我尝试了您的确切代码,它运行良好。

我认为你在一个奇怪的目录中
(如需要特殊权限的程序文件)

你为什么不尝试通过任务管理器结束 explorer.exe,
而不是再次运行您的代码?

【讨论】:

  • 如前所述,肯定不是权限问题,否则会报错。
  • 可能,但你永远不知道 ;)
【解决方案3】:

我是 Python 的新手,但我的方法对我有用。 代码如下:

from Tkinter import *
from PIL import Image,ImageTk
import os
import platform
import webbrowser

sys = platform.system()


def setup_window():
    global window
    window = Tk()
    window.geometry("300x150")
    window.title("Computer Utility GUI")


def style_window():
    path = "/home/pi/Desktop/tool icon"
    img = ImageTk.PhotoImage(Image.open(path))
    label = Label(window, image = img)
    label.grid(row=0,column=0,sticky=W)

setup_window()
style_window()

window.mainloop()

我是如何让它工作的:

1) (您需要导入 os,但在我的代码中我已经这样做了。)在运行我的代码时,我从生成的 shell 窗口中输入 os.getcwd()

这将为您提供当前工作目录。

2) 确保您的文件保存在此目录中;使用您的 Python 脚本。

3) 将运行目录输入到您需要使用它的括号中,然后在末尾添加一个斜杠并等待。

4) 应该会出现一个小部件,使用箭头键向下并找到应该保存在路径中的图像。 然后在选择它时按回车,这就是你需要使用的路径,

5)希望它应该工作。我发现 Python 不需要结尾。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 2023-04-03
    • 2011-01-24
    • 1970-01-01
    相关资源
    最近更新 更多