使用 filedialog - 我将如何调整图像大小

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

我收到此错误是否有原因?请指教。


HUX布斯
浏览 153回答 1
1回答

小怪兽爱吃肉

你必须file=删除PhotoImageself.photo&nbsp;=&nbsp;ImageTk.PhotoImage(self.resized_img)file=&nbsp;需要文件名,而不是对象&nbsp;Image()effbot.org:照片图像
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python