2017-08-10 59 views
1

我是python的新手。我正在学习如何将图像添加到我的Tkinter文件中。然而,当我尝试运行下面的代码时,解释器返回错误:FileNotFoundError:[Errno 2]没有这样的文件或目录:lee.jpg如何在Python中打开图像

我推测我需要一个更具体的路径,并且已经确保文件和图像位于相同的文件夹中。任何解释将不胜感激。

from tkinter import * 
    from PIL import ImageTk, Image 

    #Main Window 
    window = Tk() 
    window.title("Join") 
    window.geometry("800x600") 
    window.configure(background='white') 

    path = "lee.jpg" # I believe this is causing issues 

    #Makes image Tkinter-compatible 
    img = ImageTk.PhotoImage(Image.open(path)) 


    panel = Label(window, image=img) 


    panel.pack(side="bottom", fill="both", expand="yes") 

    #Start 
    window.mainloop() 
+0

感谢编辑 –

回答

0

这其实是非常简单的,可以用下面的方式实现:

from tkinter import * #imports tkinter 

root = Tk() #establishes root as the Tk window 

image = PhotoImage(file="lee.jpg") #imports image from file 
label = Label(root, image=image) #creates a Label object containing the image 

label.pack() #packs the Label into the Tk window 

root.mainloop() #starts event loop 

这可能是实现预期结果的最简单的方法。

如果您是Python的新手,我会建议您使用免费教程而不是Stack Overflow,如果您是tKinter的新手,那么http://effbot.org/tkinterbook是您的朋友。

+0

感谢您的回复。 Tkinter网站看起来会很有帮助。但是,控制台仍然返回相同的错误:无法打开“lee.jpg”:没有这样的文件或目录。我应该创建一个只包含代码和文件的新文件夹吗? –

+0

不,只要在与脚本相同的文件夹中有一个文件名“lee.jpg”,并且文件可以被读取,上面的脚本将打开图像 –