首页 > 解决方案 > 错误“图像”没有属性“打开”,但它应该

问题描述

我使用 PIL 和 TKinter 打开图像。我不明白为什么我会收到此错误

import os
import random
from PIL import Image
import time
from tkinter import *

root = Tk()

def timer(mins):
    time.sleep(mins * 60)

def anmuViewer():
    random_pic = (random.choice(os.listdir("D:/de_clutter/memez/anmu")))
    openPic = Image.open('D:/de_clutter/memez/anmu/' + random_pic)
    openPic.show()

    timer(3)

start_btn = Button(root, text = "Start", command = anmuViewer)
start_btn.pack()

root.mainloop()

应该发生的是一个 tkinter 窗口应该只弹出一个名为“开始”的按钮。当我单击该按钮时,应该会弹出一个带有图像的新窗口。相反,我收到此错误

line 17, in anmuViewer
    openPic = Image.open('D:/de_clutter/memez/anmu/' + random_pic)
AttributeError: type object 'Image' has no attribute 'open'

标签: pythontkinterpython-imaging-library

解决方案


就像 Michael Butscher 说的,

“tkinter.Image”覆盖模块命名空间中的“PIL.Image”。避免使用*

但是如果你必须使用通配符导入,在 PIL 之前导入 tkinter 应该可以解决你的问题

from tkinter import *
import os
import random
from PIL import Image
import time

推荐阅读