Python 开罗和特金特?
是否可以在开罗曲面上绘制,然后将其显示为tkinter.PhotoImage?有人能举个例子或者至少描述一下如何做到这一点吗?有很多方法可以达到你的目的,而tkinter.PhotoImage肯定不是最好的方法,除非你真的必须使用它。最简单的方法是使用: 否则,您可以通过将cairo的曲面转换为base64编码的GIF图像(在枕头的帮助下或手动,这将有点费时)并将结果作为“数据”参数传递给tkinter.PhotoImage构造函数(未测试!): 注意:在big-endian机器上,源数据AFAIK应使用“ARGB”模式Python 开罗和特金特?,python,tkinter,cairo,Python,Tkinter,Cairo,是否可以在开罗曲面上绘制,然后将其显示为tkinter.PhotoImage?有人能举个例子或者至少描述一下如何做到这一点吗?有很多方法可以达到你的目的,而tkinter.PhotoImage肯定不是最好的方法,除非你真的必须使用它。最简单的方法是使用: 否则,您可以通过将cairo的曲面转换为base64编码的GIF图像(在枕头的帮助下或手动,这将有点费时)并将结果作为“数据”参数传递给tkinter.PhotoImage构造函数(未测试!): 注意:在big-endian机器上,源数据AFA
from tkinter import Tk, Label
from PIL import Image, ImageTk
from cairo import ImageSurface, Context, FORMAT_ARGB32
class ExampleGui(Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
w, h = 800, 600
self.geometry("{}x{}".format(w, h))
self.surface = ImageSurface(FORMAT_ARGB32, w, h)
self.context = Context(self.surface)
# Draw something
self.context.scale(w, h)
self.context.rectangle(0, 0, 1, 1)
self.context.set_source_rgba(1, 0, 0, 0.8)
self.context.fill()
self._image_ref = ImageTk.PhotoImage(Image.frombuffer("RGBA", (w, h), self.surface.get_data(), "raw", "BGRA", 0, 1))
self.label = Label(self, image=self._image_ref)
self.label.pack(expand=True, fill="both")
self.mainloop()
if __name__ == "__main__":
ExampleGui()
from io import BytesIO
from PIL import Image
from cairo import ImageSurface, Context, FORMAT_ARGB32
w, h = 800, 600
surface = ImageSurface(FORMAT_ARGB32, w, h)
context = Context(surface)
output = io.BytesIO()
image = Image.frombuffer("RGBA", (w, h), self.surface.get_data(), "raw", "BGRA", 0, 1)
image.save(output, format="gif")
b64 = base64.b64encode(output.read())