Skip to main content
 首页 » 编程设计

python之如何将 png 图像转换为 gif 图像

2024年10月01日6davidwang456

我想使用 python3.6 将 png 图像更改为 gif 图像,我该怎么做?我正在用 tkinter 制作一个 GUI 程序,我不得不将 png 更改为 gif 图像,以便我可以在我的程序上显示,请帮忙

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() 

请您参考如下方法:

您可以使用 pillow 的 ImageTk 将图像直接加载为 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() 

与 tkinter 的 PhotoImage 不同,它限制您只能使用特定类型的图像,包括广泛使用的 gif 文件,ImageTk 的 PhotoImage 可以通过首先加载 pillow 来获取任何 PIL 可识别的图像类型。

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

如果您还没有枕头,请执行 pip install pillow


已添加:(感谢 Mike - SMT 的宝贵意见)

在 tk/tkl 8.6+ 的较新版本中,tk 原生支持 png 图像格式。

警告:某些 python 解释器不支持此版本的 tk。

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