在尝试通过Tkinter在画布上创建包含图像的应用程序时,我在调整图像大小时遇到了一些问题。第一个是“从PIL导入Image,ImageTk”在PyCharm IDE中不起作用,并显示“ ModuleNotFoundError:没有名为'PIL'的模块”。第二个对我来说是无法理解的,因为我是编码的新手。当我运行在cmd中提到的python文件时,发生了这种情况。您能帮助我理解问题以及如何解决吗?
码:
from tkinter import*
import tkinter
from PIL import Image, ImageTk
image = Image.open("BG.png")
image = image.resize((500,500), Image.ANTIALIAS)
#self.pw.pic = ImageTk.PhotoImage(image)
myCanvas = Canvas(root, bg = "white", height=600, width = 600)
myCanvas.place(x=550,y=100)#pack()
myCanvas.create_image(0,0, image=image,anchor="nw")
myCanvas.place(x=550, y=100)
app=Window(root)
root.mainloop()
在cmd中显示的错误:
File "tk.py", line 50, in <module>
myCanvas.create_image(0,0, image=image,anchor="nw")
File "C:\Users\hahik_zvw4rds\anaconda3\lib\tkinter\__init__.py", line 2785, in create_image
return self._create('image', args, kw)
File "C:\Users\hahik_zvw4rds\anaconda3\lib\tkinter\__init__.py", line 2771, in _create
return self.tk.getint(self.tk.call(
_tkinter.TclError: image "<PIL.Image.Image image mode=RGBA size=500x500 at 0x1A1BB564550>" doesn't exist
您注释掉的代码是正确的。您需要将Image转换为PhotoImage以便tkinter能够使用它。
from tkinter import*
import tkinter
from PIL import Image, ImageTk
image = Image.open("BG.png")
image = image.resize((500,500), Image.ANTIALIAS)
pic = ImageTk.PhotoImage(image)
myCanvas = Canvas(root, bg = "white", height=600, width = 600)
myCanvas.place(x=550,y=100)#pack()
myCanvas.create_image(0,0, image=pic, anchor="nw")
myCanvas.place(x=550, y=100)
myCanvas.image=pic
app=Window(root)
root.mainloop()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句