Skip to main content
 首页 » 编程设计

python之PhotoImage 中的透明度错误

2025年05月04日9telwanggs

我有两段代码,它们都应该创建包含黑色方 block 的 test.png。第一个这样做,但第二个返回一个透明的正方形。它们的区别在于第一个左边有明显的条纹,第二个没有。

第一个例子:

root = Tk() 
image = PhotoImage(width = 50, height = 50) 
for x in range(1, 50): 
    for y in range(50): 
        pixel(image, (x,y), (0,0,0)) 
image.write('test.png', format='png') 

第二个例子:

root = Tk() 
image = PhotoImage(width = 50, height = 50) 
for x in range(50): 
    for y in range(50): 
        pixel(image, (x,y), (0,0,0)) 
image.write('test.png', format='png') 

我还导入了 tkinter 并使用了函数 pixel(),它具有以下代码:

def pixel(image, pos, color): 
    """Place pixel at pos=(x,y) on image, with color=(r,g,b).""" 
    r,g,b = color 
    x,y = pos 
    image.put("#%02x%02x%02x" % (r,g,b), (x, y)) 

请您参考如下方法:

简而言之:Tkinter 的 PhotoImage 类不能真正保存 PNG。它只支持 GIF、PGM 和 PPM。您可能已经注意到预览图像的颜色正确,但当您打开文件时,它是空白的。

要保存 PNG 图像,您必须使用 Python 图像库,或者对于 Python 3,Pillow . 有了这个,图像创建就更容易了:

from PIL import Image 
 
image = Image.new("RGB", (50, 50), (0,0,0)) 
image.save('test.png', format='PNG') 

如果需要,可以将其转换为PIL的ImageTk.PhotoImage对象,可以在Tkinter中使用。