【问题标题】:Error 'Image' has no attribute 'open' but it should错误“图像”没有属性“打开”,但它应该
【发布时间】:2021-02-25 02:24:12
【问题描述】:

我正在使用 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'

【问题讨论】:

  • "tkinter.Image" 覆盖模块命名空间中的 "PIL.Image"。避免使用 * 导入。
  • 这就是不应该使用通配符导入的原因。

标签: python tkinter python-imaging-library


【解决方案1】:

就像 Michael Butscher 所说,

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

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

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

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 2020-09-01
    • 1970-01-01
    • 2019-05-16
    • 2021-05-30
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多