PIL 图像加载器导入失败

问题描述 投票:0回答:1

各位程序员大家好!

今天我开始使用 Tk 和 Pillow 开发一个图像导入器,用于将图像上传到小窗口中的图像并将其显示为 PNG/JPG,但是,窗口中出现错误(上传失败)。

这是它在 Python TK 窗口中显示的错误:我完全希望在窗口屏幕中看到图像显示。

`Failed to open image Module 'PilImage' has no attribute 'photoexample.jpg
python

from PIL import Image
import tkinter as tk
from tkinter import filedialog, messagebox



def import_image():
    # Open a file dialog to choose an image file
    file_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg; *.jpeg; *.png; *.gif")])

    try:
        
        image = Image.open(file_path)

        
        window = tk.Toplevel(root)

        
        window.geometry(f"{image.width}x{image.height}")

        
        label = tk.Label(window)
        label.pack()

        
        photo = Image.PhotoImage(image)

        
        label.config(image=photo)

        
        label.image = photo
    except Exception as e:
        messagebox.showerror("Error", f"Failed to open image\n{str(e)}")

root = tk.Tk()


import_button = tk.Button(root, text="Import Image", command=import_image)
import_button.pack()

root.mainloop()

我接受任何帮助/支持。

谢谢!

python tkinter python-imaging-library
1个回答
0
投票

今天我开始使用 Tk 和 Pillow 开发图像导入器 将图像上传到小窗口中的图像并显示为 PNG/JPG,但是,窗口中出现错误(上传失败)。

问题可以解决。

  • 添加命名空间
    ImageTk
  • Image.PhotoImage
    替换为:
    ImageTk.PhotoImage

片段:

from PIL import Image, ImageTk
import tkinter as tk
from tkinter import filedialog, messagebox



def import_image():
    # Open a file dialog to choose an image file
    file_path = filedialog.askopenfilename(filetypes=[("Open files", "*.jpg; *.jpeg; *.png; *.gif")])

    try:
        
        image = Image.open(file_path)

        
        window = tk.Toplevel(root)

        
        window.geometry(f"{image.width}x{image.height}")

        
        label = tk.Label(window)
        label.pack()

        
        photo = ImageTk.PhotoImage(image)

        
        label.config(image=photo)

        
        label.image = photo
    except Exception as e:
        messagebox.showerror("Error", f"Failed to open image\n{str(e)}")

root = tk.Tk()


import_button = tk.Button(root, text="Import Image", command=import_image)
import_button.pack()

root.mainloop()

不使用 Tkinter:

片段:

# Imports PIL module 
from PIL import Image


# open method used to open different extension image file 
im = Image.open("p2.png") 

# This method will show image in any image viewer 
im.show()

截图:

© www.soinside.com 2019 - 2024. All rights reserved.