Search code examples
pythonpython-3.xtkinterphotoimage

how can I make png image to gif image?


I want to change png image to gif image using python3.6 how can I do that? i'm making a GUI program with tkinter and i haver to change png to gif image so i can display on my program please help

tk = Tk()
tk.configure(bg = 'white')

tk.title("SearchKeyWord V2.0")

canvas = Canvas(tk,width = 880, height = 550,bd = 0,highlightthickness = 0)

canvas.pack()
txt = Entry(tk)
txt.place(relx = .9,rely = .3,anchor = "c")
LOGO = PhotoImage(file = 'SKW-LOGO.gif')
button_1 = PhotoImage(file = 'button.gif')
button_2 = PhotoImage(file = 'button_news_1d.gif')
button_3 = PhotoImage(file = 'button_news_1w.gif')




button = tkinter.Button(tk,image = button_1,command = search)
button_news_1d = tkinter.Button(tk,image = button_2)
button_news_1w = tkinter.Button(tk,image = button_3)

canvas.create_image(0,0,anchor = NW, image = LOGO)
button.place(relx=.8, rely=.5, anchor="c")
button_news_1d.place(relx =.8,rely = .7, anchor = "c" )
button_news_1w.place(relx =.8,rely = .9, anchor = "c" )


tk.update()
tk.mainloop()

Solution

  • You can use pillow’s ImageTk to load the image directly as png.

    import tkinter as tk
    from PIL import Image, ImageTk
    image_o = Image.open("photo.png")
    image = ImageTk.PhotoImage(image_o)
    
    #  Use image as to how you would in tkinter 
    
    root = tk.Tk()
    button = tk.Button(root, image = image)
    button.pack()
    root.mainloop()
    

    Unlike tkinter‘s PhotoImage, which limits you to use only a certain type of images including the widespread gif file, ImageTk’s PhotoImage can take any PIL recognizable image type by having pillow to load it first.

    http://pillow.readthedocs.io/en/4.1.x/reference/ImageTk.html

    If you don’t have pillow yet, do pip install pillow


    Added: (thanks to Mike - SMT’s valuable comment)

    In newer releases of tk/tkl 8.6+, tk natively supports png image format.

    Warning: this version of tk isn’t supported in some python interpreters.

    https://www.tcl.tk/software/tcltk/8.6.html