Putting .SVG images into tkinter Frame
I have finally managed to convert SVGs with Python 3 and PyCairo on Windows, but without rsvg. Rsvg still won't cooperate, but apparently it is still possible to load SVGs without it.
The installation process is not very straightforward, but hey, it works!
Instructions:
Note that these instructions are Windows-specific. On Linux, one can simply install pycairo via pip and use PyGObject's rsvg.
- Download the pycairo .whl file for your Windows installation from https://www.lfd.uci.edu/~gohlke/pythonlibs/.
- Install the downloaded file via pip:
pip install /path/to/your/pycairo/whl.whl
If that doesn't work, try using a different file from the above link. It may take a few tries. - Run
pip install tinycss cssselect2 defusedxml
. This will install the dependacies for the next step. - Go to https://github.com/Kozea/CairoSVG. Download and extract the
cairosvg
folder to your site packages folder, enabling your code to import it. - Go to the
cairosvg
folder and open the filesurface.py
. - Look for the line that says
import cairocffi as cairo
and replace it withimport cairo
That should be enough to use PyCairo on Windows without a C++ compiler. Unfortionately, this still doesn't fix the rsvg issues (instead it replaces rsvg), but at least it works.
Here are some examples of how to use it:
To convert an SVG to a PNG:
import cairosvg
cairosvg.svg2png(url="example.svg", write_to="output.png")
To put an SVG into a Tkinter window without downloading the output:
import cairosvg
import io
import tkinter as tk
from PIL import Image,ImageTk
main=tk.Tk()
image_data = cairosvg.svg2png(url="example.svg")
image = Image.open(io.BytesIO(image_data))
tk_image = ImageTk.PhotoImage(image)
button=tk.Label(main, image=tk_image)
button.pack(expand=True, fill="both")
main.mainloop()
Since it still uses Cairo, this solution is very quick, and has few dependencies.
Hopefully this answer will be useful for anyone reading this in the future!
I've managed to do it using svglib:
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM
drawing = svg2rlg("safari-pinned-tab.f387b3f2.svg")
renderPM.drawToFile(drawing, "temp.png", fmt="PNG")
from tkinter import *
tk = Tk()
from PIL import Image, ImageTk
img = Image.open('temp.png')
pimg = ImageTk.PhotoImage(img)
size = img.size
frame = Canvas(tk, width=size[0], height=size[1])
frame.pack()
frame.create_image(0,0,anchor='nw',image=pimg)
tk.mainloop()