将.SVG图像放入tkinter Frame

And*_*doo 9 python tkinter cairo rsvg python-3.x

我一直在尝试将来自https://betacssjs.chesscomfiles.com/bundles/web/favicons/safari-pinned-tab.f387b3f2.svg的图像放入Tkinter框架。我从这里的帖子中发现,在rsvg和cairo的帮助下,这是可能的。

我使用python 3.6在Windows 10,我RSVG从这里和开罗这里,然后提取该文件夹复制到“C:\用户\ site_packages”文件夹。他们进口罚款,但我不知道如何使用它们。我尝试使用代码:

import tkinter as tk
main=tk.Tk()
frame=tk.Frame(main)
def svgPhotoImage(self,file_path_name):
        from PIL import Image,ImageTk
        import rsvg,cairo 
        svg = rsvg.Handle(file=file_path_name)
        width, height = svg.get_dimension_data()[:2]
            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(width), int(height))
            context = cairo.Context(surface)
            #context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
            svg.render_cairo(context)
            tk_image=ImageTk.PhotoImage('RGBA')
            image=Image.frombuffer('RGBA',(width,height),surface.get_data(),'raw','BGRA',0,1)
            tk_image.paste(image)
            return(tk_image)
    tk_image=self.svgPhotoImage(filename)
    frame.configure(image=tk_image)
Run Code Online (Sandbox Code Playgroud)

#rsvg.py
import os
try:
    import rsvg
    WINDOWS=False
except ImportError:
    print"Warning, could not import 'rsvg'"
    if os.name == 'nt':
        print "Detected windows, creating rsvg."
        #some workarounds for windows

        from ctypes import *

        l=CDLL('librsvg-2-2.dll')
        g=CDLL('libgobject-2.0-0.dll')
        g.g_type_init()

        class rsvgHandle():
            class RsvgDimensionData(Structure):
                _fields_ = [("width", c_int),
                            ("height", c_int),
                            ("em",c_double),
                            ("ex",c_double)]

            class PycairoContext(Structure):
                _fields_ = [("PyObject_HEAD", c_byte * object.__basicsize__),
                            ("ctx", c_void_p),
                            ("base", c_void_p)]

            def __init__(self, path):
                self.path = path
                error = ''
                self.handle = l.rsvg_handle_new_from_file(self.path,error)


            def get_dimension_data(self):
                svgDim = self.RsvgDimensionData()
                l.rsvg_handle_get_dimensions(self.handle,byref(svgDim))
                return (svgDim.width,svgDim.height)

            def render_cairo(self, ctx):
                ctx.save()
                z = self.PycairoContext.from_address(id(ctx))
                l.rsvg_handle_render_cairo(self.handle, z.ctx)
                ctx.restore()



        class rsvgClass():
            def Handle(self,file):
                return rsvgHandle(file)

        rsvg = rsvgClass()).
h = rsvg.Handle("box.svg")
s = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
ctx = cairo.Context(s)
h.render_cairo(ctx)
Run Code Online (Sandbox Code Playgroud)

在尝试了这些脚本之后,我不断收到错误消息:

AttributeError: module 'rsvg' has no attribute 'Handle'
Run Code Online (Sandbox Code Playgroud)

我确定我在此过程中做错了事,但是经过数小时的搜索仍然无法弄清楚如何使其工作。我也尝试安装pycairo(通过pip),但收到错误消息

ERROR: Command "'c:\...\python36-32\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\...\\pip-install-peqhj3x1\\pycairo\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\...\Temp\pip-record-jfozfbuc\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\...\pip-install-peqhj3x1\pycairo\
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么办

编辑:我终于能够从https://www.lfd.uci.edu/~gohlke/pythonlibs/获取pycairo ,现在可以正常使用了。我终于得到rsvg,通过参考这里没有给我以上错误消息, 并从这里得到了必要的DLL文件 。开罗工作正常,但RSVG正在创建黑屏。在这里尝试了另一个7班轮 并得到了一个空白文件的输出,而不是转换后的文件。显然RSVG无法正常工作,我认为这是一个安装问题(例如,不正确的.dll)。救命?

如果要使用cairo和rsvg是因为它们占用的空间很小并且速度很快;棒或其他库不是一个选择。我只希望能够将SVG文件放入tkinter框架中。如果有人知道如何正确安装rsvg,我将不胜感激。

任何帮助将不胜感激。感谢您的任何建议。

Бог*_*пир 5

我已经成功地使用 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()

Run Code Online (Sandbox Code Playgroud)


And*_*doo 1

我终于成功地在 Windows 上使用 Python 3 和 PyCairo 转换 SVG,但没有 rsvg。Rsvg 仍然不会合作,但显然仍然可以在没有它的情况下加载 SVG。

\n

安装过程不是很简单,但是嘿,它有效!

\n

\xc2\xa0

\n

指示:

\n

请注意,这些说明是特定于 Windows 的。在 Linux 上,可以简单地通过 pip 安装 pycairo 并使用 PyGObject\ 的 rsvg。

\n
    \n
  1. 从https://www.lfd.uci.edu/~gohlke/pythonlibs/下载适用于 Windows 安装的 pycairo .whl 文件。
  2. \n
  3. 通过 pip 安装下载的文件:pip install /path/to/your/pycairo/whl.whl如果这不起作用,请尝试使用上述链接中的其他文件。可能需要尝试几次。
  4. \n
  5. 跑步pip install tinycss cssselect2 defusedxml。这将为下一步安装依赖项。
  6. \n
  7. 转到https://github.com/Kozea/CairoSVG。下载该文件夹并将其解压cairosvg到您的站点包文件夹中,以便您的代码能够导入它。
  8. \n
  9. 转到cairosvg文件夹并打开文件surface.py
  10. \n
  11. 查找显示的行import cairocffi as cairo并将其替换为import cairo
  12. \n
\n

这应该足以在 Windows 上使用 PyCairo,无需 C++ 编译器。不幸的是,这仍然不能解决 rsvg 问题(而是取代 rsvg),但至少它可以工作。

\n

\xc2\xa0

\n

以下是一些如何使用它的示例:

\n

要将 SVG 转换为 PNG:

\n
import cairosvg\ncairosvg.svg2png(url="example.svg", write_to="output.png")\n
Run Code Online (Sandbox Code Playgroud)\n

要将 SVG 放入 Tkinter 窗口而不下载输出:

\n
import cairosvg\nimport io\nimport tkinter as tk\nfrom PIL import Image,ImageTk\n\nmain=tk.Tk()\n\nimage_data = cairosvg.svg2png(url="example.svg")\nimage = Image.open(io.BytesIO(image_data))\ntk_image = ImageTk.PhotoImage(image)\n\nbutton=tk.Label(main, image=tk_image)\nbutton.pack(expand=True, fill="both")\nmain.mainloop()\n
Run Code Online (Sandbox Code Playgroud)\n

\xc2\xa0

\n

由于它仍然使用 Cairo,因此该解决方案非常快,并且依赖性很少。

\n

希望这个答案对将来阅读本文的人有用!

\n