I want to import a png image but i'm unable to write imagetype as an argument for the Image function the correct way. I've tried writing "png", "PNG", imgtype="png" but it wont work. Does anybody know how to write this correctly. I'm using the code below. I'm using OSX btw.
from Tkinter import *
import PIL
root = Tk()
img = Image("this is where i'm supppsed to write imgtype", file="image.png")
panel = Canvas(root)
panel.pack(side = "bottom", fill = "both", expand = "yes")
panel.create_image(image=img)
root.mainloop()
You are trying to create an image from tkinters Image
class but it doesn't support .png
images.
From the documentation :
The PhotoImage class can read GIF and PGM/PPM images from files:
photo = PhotoImage(file="image.gif")
If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects:
from PIL import Image, ImageTk image = Image.open("lenna.jpg") photo = ImageTk.PhotoImage(image)
By doing from Tkinter import *
, you are loading all modules from the Tkinter
package into the global namespace, so Image
in your case is actually Tkinter.Image
.
To fix your issue, try:
pil_img = PIL.Image.open("image.png")
img = PIL.ImageTk.PhotoImage(pil_img)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.