#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2022/03/22 21:58:42 +0900> """ pycairo in tkinter. python - Cairo with tkinter? - Stack Overflow https://stackoverflow.com/questions/25480853/cairo-with-tkinter * Windows10 x64 21H2 + Python 2.7.18 32bit + Pillow 6.2.2 + pycairo 1.8.10 * Windows10 x64 21H2 + Python 3.9.11 64bit + Pillow 9.0.1 + pycairo 1.21.0 """ import sys if sys.version_info.major == 2: # Python 2.7 import Tkinter as tk else: # Python 3.x import tkinter as tk from PIL import Image from PIL import ImageTk import cairo def conv_surface_to_photo(surface): """Convert pycairo surface to Tk PhotoImage.""" w, h = surface.get_width(), surface.get_height() m = surface.get_data() if sys.version_info.major == 2: # Python 2.7 im = Image.frombuffer("RGBA", (w, h), m, "raw", "BGRA", 0, 1) else: # Python 3.x im = Image.frombuffer("RGBA", (w, h), m, "raw", "RGBA", 0, 1) # BGRA -> RGBA r, g, b, a = im.split() im = Image.merge("RGBA", (b, g, r, a)) # data = im.tobytes("raw", "BGRA", 0, 1) # im = Image.frombytes("RGBA", (w, h), data) return ImageTk.PhotoImage(im) def main(): print(sys.version) w, h = 640, 480 root = tk.Tk() # root.geometry("{}x{}".format(w, h)) root.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) w = root.surface.get_width() h = root.surface.get_height() # draw something with pycairo ctx = cairo.Context(root.surface) ctx.scale(w, h) ctx.rectangle(0, 0, 0.5, 0.5) ctx.set_source_rgba(1, 0, 0, 0.8) ctx.fill() ctx.rectangle(0.5, 0, 0.5, 0.5) ctx.set_source_rgba(0, 1, 0, 0.8) ctx.fill() ctx.rectangle(0, 0.5, 0.5, 0.5) ctx.set_source_rgba(0, 0, 1, 0.8) ctx.fill() # convert cairo image surface to tk.PhotoImage root._image_ref = conv_surface_to_photo(root.surface) label = tk.Label(root, image=root._image_ref) label.pack(expand=True, fill="both") root.mainloop() if __name__ == "__main__": main()