本文介绍了将.SVG图像放入tkinter框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试从 https中放置图片://betacssjs.chesscomfiles.com/bundles/web/favicons/safari-pinned-tab.f387b3f2.svg 插入Tkinter框架.我从这儿找到在rsvg和cairo的帮助下是可能的.

I have been trying to put the image from https://betacssjs.chesscomfiles.com/bundles/web/favicons/safari-pinned-tab.f387b3f2.svg into a Tkinter frame. I found from the post here that it is possible with the help from rsvg and cairo.

我在Windows 10上使用python 3.6.我从此处获取了rsvg,并从,然后将文件夹提取到"C:\ Users ... \ site_packages"文件夹中.他们进口罚款,但我不知道如何使用它们.我尝试使用代码:

I was using python 3.6 on Windows 10. I got rsvg from here and cairo from here and then extracted the folders to the 'C:\Users...\site_packages' folder. They import fine but I cannot figure out how to use them. I tried using the code:

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)

#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)

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

After trying those scripts, I kept getting the error message:

AttributeError: module 'rsvg' has no attribute 'Handle'

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

I am sure I did something wrong in the process but after hours of searching still could not figure out how to get it to work. I also tried installing pycairo (via pip) but got the error message

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\

我不知道现在该怎么办

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

If am trying to use cairo and rsvg because they take up little space and are really fast; wand or some other library is not an option. I just want to be able to put an SVG file into a tkinter frame. If anyone knows how install rsvg properly, I'd appreciate knowing.

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

Any help would be hugely appreciated.Thank you for any suggestions.

推荐答案

我终于设法在Windows上使用Python 3和PyCairo转换了SVG,但没有rsvg.Rsvg仍然无法配合,但是显然,没有它,仍然可以加载SVG.

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!

说明:

请注意,这些说明特定于Windows.在Linux上,只需通过pip安装pycairo并使用PyGObject的rsvg.

Note that these instructions are Windows-specific. On Linux, one can simply install pycairo via pip and use PyGObject's rsvg.

  1. https://www下载用于Windows安装的pycairo .whl文件.lfd.uci.edu/~gohlke/pythonlibs/.
  2. 通过pip安装下载的文件: pip install/path/to/your/pycairo/whl.whl 如果不起作用,请尝试使用上述链接中的其他文件.可能需要尝试一些.
  3. 运行 pip install tinycss cssselect2 defusedxml .这将为下一步安装依赖项.
  4. 转到 https://github.com/Kozea/CairoSVG .将 cairosvg 文件夹下载并解压缩到您的站点包文件夹中,以使您的代码能够导入它.
  5. 转到 cairosvg 文件夹并打开文件 surface.py .
  6. 查找显示为 import cairocffi as cairo 的行,并将其替换为 import cairo
  1. Download the pycairo .whl file for your Windows installation from https://www.lfd.uci.edu/~gohlke/pythonlibs/.
  2. 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.
  3. Run pip install tinycss cssselect2 defusedxml. This will install the dependacies for the next step.
  4. Go to https://github.com/Kozea/CairoSVG. Download and extract the cairosvg folder to your site packages folder, enabling your code to import it.
  5. Go to the cairosvg folder and open the file surface.py.
  6. Look for the line that says import cairocffi as cairo and replace it with import cairo

这足以在没有C ++编译器的Windows上使用PyCairo.幸运的是,这仍然不能解决rsvg问题(相反,它代替了rsvg),但至少可以解决问题.

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.

以下是一些使用方法的示例:

要将SVG转换为PNG:

To convert an SVG to a PNG:

import cairosvg
cairosvg.svg2png(url="example.svg", write_to="output.png")

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

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()

由于它仍然使用Cairo,因此该解决方案非常快捷,并且几乎没有依赖项.

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!

这篇关于将.SVG图像放入tkinter框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 09:15
查看更多