简体   繁体   English

如何使用 Python 中的 Tkinter 调整 Canvas 中的图像大小?

[英]How can I resize an image within Canvas with Tkinter in Python?

While trying to create an app including an image within a canvas by Tkinter, I got some problems with resizing the image.在尝试通过 Tkinter 创建一个包含 canvas 中的图像的应用程序时,我在调整图像大小时遇到了一些问题。 The first one is that "from PIL import Image, ImageTk" does not work in PyCharm IDE, and shows "ModuleNotFoundError: No module named 'PIL'".第一个是“from PIL import Image, ImageTk”在 PyCharm IDE 中不起作用,并显示“ModuleNotFoundError: No module named 'PIL'”。 The second one is not understandable for me since I am a novice in coding.第二个对我来说是无法理解的,因为我是编码新手。 It happened when I run the python file that I mentioned in cmd.它发生在我运行我在 cmd 中提到的 python 文件时。 Could you help me to understand the problem and what I can do with it?你能帮我理解这个问题以及我能做些什么吗?

Code:代码:

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()

Error shown in cmd: 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

Your commented out code is correct.您注释掉的代码是正确的。 You need to convert the Image to a PhotoImage for tkinter to be able to use it.您需要将 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM