无法在python中加载图像

时间:2016-11-03 19:11:27

标签: python image canvas tkinter

我正在尝试将图像加载到python中的画布中。但是我收到错误:TclError:无法识别图像文件中的数据“C:\ testimage \ spongesea.jpg”

import Tkinter
from Tkinter import *
import time
import inspect
import os
from PIL import Image, ImageTk

class game_one:

    def __init__(self):

        global root 
        global canvas_one
        root = Tk() 
        root.title("   Thanks Josh Dark
        canvas_one = Tkinter.Canvas(root, bg="BLACK")
        canvas_one.pack(expand= YES, fill= BOTH)
        canvas_one.focus_set() #allows keyboard events
        p = PhotoImage(file="C:\testimage\spongesea.jpg")
        canvas_one.create_image(0, 0, image = p, anchor=NW)
        root.grab_set()#I forget what this does.  Don't change it.
        root.lift()#This makes root appear in front of the other applications

ObjectExample = game_one()# starts the animation

我可以从文件中手动打开图像,因此它没有损坏,并且它正在调用正确的位置。有任何想法吗?感谢

1 个答案:

答案 0 :(得分:1)

PhotoImage仅适用于GIFPGM/PPM

您必须使用ImageImageTk来处理其他格式

from PIL import Image, ImageTk

image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)

BTW:阅读PhotoImage并在注释中看到“垃圾收集问题”。