[英]Cairo with tkinter?
是否可以在開羅表面上繪圖然后將其顯示為tkinter.PhotoImage? 有人可以提供一個例子,或至少描述一個人如何做到這一點?
有很多方法可以實現你想要的東西和tkinter.PhotoImage肯定不是最好的方法,除非你真的必須使用它。 最簡單的方法是使用Pillow庫中的ImageTK模塊 :
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()
否則你可以通過將cairo的表面轉換為base64編碼的GIF圖像(在Pillow的幫助下或手動,這將有點耗時)並將結果作為“data”arg傳遞給tkinter.PhotoImage構造函數來實現。 ( 未經測試! ):
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())
注意:在big-endian機器上,“ARGB”模式應該用於源數據AFAIK。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.