How to open PIL Image in Tkinter on Canvas

后端 未结 4 1135
面向向阳花
面向向阳花 2021-02-14 18:08

I can\'t seem to get my PIL Image to work on canvas. Code:

from Tkinter import*
import Image, ImageTk
root = Tk()
root.geometry(\'1000x1000\')
canvas = Canvas(ro         


        
相关标签:
4条回答
  • 2021-02-14 18:26

    Try creating a PIL Image first, then using that to create the PhotoImage.

    from Tkinter import *
    import Image, ImageTk
    root = Tk()
    root.geometry('1000x1000')
    canvas = Canvas(root,width=999,height=999)
    canvas.pack()
    pilImage = Image.open("ball.gif")
    image = ImageTk.PhotoImage(pilImage)
    imagesprite = canvas.create_image(400,400,image=image)
    root.mainloop()
    
    0 讨论(0)
  • 2021-02-14 18:40

    (An old question, but the answers so far are only half-complete.)

    Read the docs:

    class PIL.ImageTk.PhotoImage(image=None, size=None, **kw)
    
    • image – Either a PIL image, or a mode string. [...]
    • file – A filename to load the image from (using Image.open(file)).

    So in your example, use

    image = ImageTk.PhotoImage(file="ball.gif")
    

    or explicitly

    image = ImageTk.PhotoImage(Image("ball.gif"))
    

    (And remember – as you did correctly: Keep a reference to the image object in your Python program, otherwise it is garbage-collected before you seee it.)

    0 讨论(0)
  • 2021-02-14 18:42

    I was banging my head against the wall for a while on this issue until I found the following:

    http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

    Apparently, Python's garbage collector can trash the ImageTk object. I imagine apps using alot of widgets (like mine) are more susceptible to this behavior.

    0 讨论(0)
  • 2021-02-14 18:47

    You can import multiple image formats, and resize with this code. "basewidth" sets the width of your image.

    from Tkinter import *
    import PIL
    from PIL import ImageTk, Image
    
    root=Tk()
    image = Image.open("/path/to/your/image.jpg")
    canvas=Canvas(root, height=200, width=200)
    basewidth = 150
    wpercent = (basewidth / float(image.size[0]))
    hsize = int((float(image.size[1]) * float(wpercent)))
    image = image.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
    photo = ImageTk.PhotoImage(image)
    item4 = canvas.create_image(100, 80, image=photo)
    
    canvas.pack(side = TOP, expand=True, fill=BOTH)
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题