2

While trying to create an app including an image within a canvas by Tkinter, I got some problems with resizing the image. The first one is that "from PIL import Image, ImageTk" does not work in PyCharm IDE, and shows "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. 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:

  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
1
  • pip install Pillow in terminal or just go to file -> settings -> python interpreter -> click on the '+' sign at the bottom then search for pillow -> install package Commented Jan 3, 2021 at 7:59

1 Answer 1

1

Your commented out code is correct. You need to convert the Image to a PhotoImage for tkinter to be able to use it.

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.