简体   繁体   中英

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?

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.

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.

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.

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