Adding a background image in python

后端 未结 3 1131
猫巷女王i
猫巷女王i 2021-01-05 15:15

I\'m trying to add a background image to a canvas in Python. So far the code looks like this:

from Tkinter import *
from PIL import ImageTk,Image

... other          


        
相关标签:
3条回答
  • 2021-01-05 15:54

    just change to :

        image = Image.open("~~~path.png")
        backgroundImage=ImageTk.PhotoImage(image)
    

    believe me this will 100% work

    0 讨论(0)
  • 2021-01-05 16:01

    PhotoImage is not an attribute of the Tk() instances (root). It is a class from Tkinter.

    So, you must use:

    backgroundImage = PhotoImage("D:\Documents\Background.gif")
    

    Beware also Label is a class from Tkinter...

    Edit:

    Unfortunately, Tkinter.PhotoImage only works with gif files (and PPM). If you need to read png files you can use the PhotoImage (yes, same name) class in the ImageTk module from PIL.

    So that, this will put your png image in the canvas:

    from Tkinter import *
    from PIL import ImageTk
    
    canvas = Canvas(width = 200, height = 200, bg = 'blue')
    canvas.pack(expand = YES, fill = BOTH)
    
    image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
    canvas.create_image(10, 10, image = image, anchor = NW)
    
    mainloop()
    

    enter image description here

    0 讨论(0)
  • 2021-01-05 16:06
    from Tkinter import *
    from PIL import ImageTk
    
    canvas = Canvas(width = 200, height = 200, bg = 'blue')
    canvas.pack(expand = YES, fill = BOTH)
    
    image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
    canvas.create_image(10, 10, image = image, anchor = NW)
    
    mainloop()
    
    0 讨论(0)
提交回复
热议问题