python - 如何在 Python 中使用 Tkinter 在 Canvas 中调整图像的大小?
问题描述
在尝试通过 Tkinter 在画布中创建包含图像的应用程序时,我在调整图像大小时遇到了一些问题。第一个是“from PIL import Image, ImageTk”在 PyCharm IDE 中不起作用,并显示“ModuleNotFoundError: No module named '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()
推荐阅读
- javascript - 尽管存在路线,但未捕获 JADE 表单提交
- .htaccess - mod_rewrite 规则 htaccess 未按预期工作
- bash - 在值之间查找多个字符串并在bash中用换行符替换
- ruby-on-rails - Rails 方法而不是模型的 has_many 中的 id
- regex - 正则表达式等于或高于 125233000
- javascript - 更新 observable 中的值而不解析先前的运算符
- java - 当我在我的 android mobile samsung j7 prime 上运行 android 项目时,手机无法授予权限
- ionic-framework - 通过 Ionic 向 Web API 发送多条记录
- javascript - 无法使用 Laravel Mix 访问 Vue 组件中的 js-cookie
- android - 为什么 Proguard 不会混淆某些包私有类?