使用filedialog调整图像大小时出现问题。
from PIL import Image, ImageTk
def fileDialog(self):
self.filename = filedialog.askopenfilename(title="Select file")
self.label = tk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text=os.path.basename(self.filename))
self.img = Image.open(self.filename)
self.resized_img = self.img.resize((200, 100))
self.photo = ImageTk.PhotoImage(file=self.resized_img)
self.display = tk.Label(image=self.photo)
self.display.grid(row=0)
之所以在filedialog函数中执行此操作,是因为在用户单击文件之前,我不知道将要选择的文件名。我这样做是Image.open(self.filename)
,因为filename
保留了文件浏览器打开后用户单击的文件名。但是,我得到这些错误。我不想做open('car.jpg')
,因为它可能是另外一张图片,这就是为什么我做open('self.filename')
。
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python37-
32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "gui.py", line 41, in fileDialog
self.photo = ImageTk.PhotoImage(file=self.resized_img)
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\PIL\ImageTk.py", line 94, in __init__
image = _get_image_from_kw(kw)
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\PIL\ImageTk.py", line 64, in _get_image_from_kw
return Image.open(source)
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\PIL\Image.py", line 2661, in open
prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read'
Exception ignored in: <function PhotoImage.__del__ at 0x03A63B70>
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\PIL\ImageTk.py", line 123, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
是否有出现此错误的原因?请指教。
答案 0 :(得分:0)
您必须删除file=
中的PhotoImage
self.photo = ImageTk.PhotoImage(self.resized_img)
file=
需要文件名,而不是对象Image()
effbot.org:PhotoImage