我有两段代码,它们都应该创建包含一个黑色方块的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并使用函数像素(),它有以下代码:
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))发布于 2014-09-08 19:45:19
简而言之:Tkinter的PhotoImage类并不能真正拯救PNG。它只支持GIF、PGM和PPM。您可能已经注意到预览图像的颜色是正确的,但是当您打开文件时,它是空白的。
要保存PNG图像,您必须使用Python,或者,对于Python3,必须使用枕头。这样,创建图像就更容易了:
from PIL import Image
image = Image.new("RGB", (50, 50), (0,0,0))
image.save('test.png', format='PNG')如果需要,可以将其转换为可以在Tkinter中使用的PIL的ImageTk.PhotoImage对象。
https://stackoverflow.com/questions/25726726
复制相似问题