从函数在 IPython 笔记本中显示 SVG

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30334385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:16:57  来源:igfitidea点击:

Display SVG in IPython notebook from a function

pythonsvgipython-notebook

提问by prooffreader

In IPython notebook, the following code displays the SVG below the cell:

在 IPython notebook 中,以下代码在单元格下方显示 SVG:

from IPython.display import SVG
SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg')

The following displays nothing:

以下内容不显示:

from IPython.display import SVG
def show_svg():
    SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg')

Is there a way to display an SVG from within a function (or a class)?

有没有办法从函数(或类)中显示 SVG?

采纳答案by Jakob

You need to displaythe SVG like

你需要display像 SVG

from IPython.display import SVG, display
def show_svg():
    display(SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg'))

You first example works as the SVG object returns itself an is subsequently displayed by the IPython display machinery. As you want to create your SVG object in a custom method, you need to take care of the displaying.
The displaycall is similar to the ordinary printstatement, but can handle different representations like images, html, latex, etc. For details have a look at the rich display documentation.

您的第一个示例在 SVG 对象返回自身时起作用,随后由 IPython 显示机制显示。由于您想以自定义方法创建 SVG 对象,因此您需要注意显示。
display调用与普通print语句类似,但可以处理不同的表示形式,如图像、html、乳胶等。有关详细信息,请查看丰富的显示文档

回答by Mike Müller

Add returnto your function :

添加return到您的功能:

from IPython.display import SVG
def show_svg():
    return SVG(url='http://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg')

Then call your functions as the last line in cell:

然后将您的函数作为单元格中的最后一行调用:

show_svg()