Dom
Dom

Reputation: 159

Python 2.7 How to add images on the canvas with Tkinter

I need to add an image to the canvas. I have tried countless amounts of things, and finally decided to make a question on here.

This is what I have imported

from Tkinter import *
import tkFont
from PIL import ImageTk, Image

And this is the line of code I'm trying to add to import an image from the same folder the main file is in.

c.create_image(100,100, anchor=N, image = ghost.jpg)

I've also tried putting ""s around 'ghost.jpg' and it says the Image does not exist then. Without the quotes it says "global name 'ghost' does not exist."

Can anyone help?

Upvotes: 0

Views: 5133

Answers (2)

L.Clarkson
L.Clarkson

Reputation: 492

from Tkinter import * 
"""python 2.7 =Tkinter"""
from PIL import Image, ImageTk
app = Tk()
temp=Image.open("photo.jpg")
temp = temp.save("photo.ppm","ppm")
photo = PhotoImage(file = "photo.ppm")
imagepanel=Label(app,image = photo)
imagepanel.grid()
app.mainloop()

This is a bit of code I wrote in python 2.7 with Tkinter and PIL to import a jpg file from a given directory, this doesn't pop up off the screen. You should replace photo with the file name (and directory) and app with the relevant variable you set.

Upvotes: 1

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

Canvas.create_image's image argument

should be a PhotoImage or BitmapImage, or a compatible object (such as the PIL's PhotoImage). The application must keep a reference to the image object.

Upvotes: 1

Related Questions