Image 如何在Python中打开图像

Image 如何在Python中打开图像,image,python-3.x,python-imaging-library,Image,Python 3.x,Python Imaging Library,我是python新手。我正在学习如何将图像添加到我的Tkinter文件中。但是,当我尝试运行以下代码时,解释器返回错误:FileNotFoundError:[Errno 2]没有这样的文件或目录:lee.jpg 我假设我需要一个更具体的路径,并且已经确保文件和图像都在同一个文件夹中。如有任何解释,将不胜感激 from tkinter import * from PIL import ImageTk, Image #Main Window window = Tk(

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

我假设我需要一个更具体的路径,并且已经确保文件和图像都在同一个文件夹中。如有任何解释,将不胜感激

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

这实际上非常简单,可以通过以下方法实现:

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新手,我建议您使用免费教程,而不是堆栈溢出,如果您是tKinter新手,则是您的朋友。

这实际上非常简单,可以通过以下方法实现:

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新手,我建议您提供一个免费教程,而不是堆栈溢出,如果您是tKinter新手,那么他就是您的朋友。

谢谢您的回复。Tkinter网站看起来将是一个很大的帮助。但是,控制台仍然返回相同的错误:无法打开“lee.jpg”:没有这样的文件或目录。我是否应该创建一个只包含代码和文件的新文件夹?不,只要脚本所在的文件夹中有一个文件名“lee.jpg”,并且文件可以读取,上述脚本将打开图像谢谢您的回复。Tkinter网站看起来将是一个很大的帮助。但是,控制台仍然返回相同的错误:无法打开“lee.jpg”:没有这样的文件或目录。我是否应该创建一个只包含代码和文件的新文件夹?不,只要脚本所在的文件夹中有文件名“lee.jpg”,并且文件可以读取,上述脚本将打开图像谢谢编辑谢谢编辑谢谢编辑