在Matplotlib图形窗口中更改图标

7

如何更改Matplotlib图形窗口的图标?我的应用程序有一个按钮,打开带有Matplotlib绘制的图形的Figure窗口。我成功地修改了应用程序的图标,但Figure窗口仍然具有Tkinter的典型“Tk”图标。


虽然不完全是您所要求的,但这里有一个在Tkinter中嵌入matplot图形的示例:http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html(也许只是为了更改图标而过度使用) - FabienAndre
@FabienAndre:谢谢,但是我不能用那个做我想要的事情。 - maupertius
2
由于您已经成功更改了常规tkinter窗口的图标,将matplotlib图形显示在tkinter小部件中可以让您在自己的Tkinter窗口(Toplevel是允许您打开窗口的小部件)中显示它,您可以更改其图标。此外,您不必使用可能提供有趣设计选择的另一个窗口。 - FabienAndre
嗯,我不太明白。我使用Tkinter应用程序(其中包含我想要的图标)中的“imshow()”创建我的图形。显然,使用“imshow()”命令弹出的窗口仍然具有TKinter徽标,而不是我的应用程序徽标。 - maupertius
听起来你正在尝试做这个:https://dev59.com/sW855IYBdhLWcg3w7o-g,也就是说`imshow()`应该从一个图形对象中的轴调用,而不是直接从pyplot模块中调用。 - deinonychusaur
5个回答

7
我这样解决了这个问题: 在我按下使用 imshow()show() 创建图像的按钮之前,我以这种方式初始化该图像:
plt.Figure()
thismanager = get_current_fig_manager()
thismanager.window.wm_iconbitmap("icon.ico")

当我按下show()时,窗口将显示我想要的图标。

1
感谢您的回答。如果您正在使用wxAgg后端,则等效的代码是thismanager.window.SetIcon(wx.Icon("mylogo.ico", wx.BITMAP_TYPE_ICO))。 - harijay

3

对我来说,之前的答案并没有起作用,而需要以下方法:

from Tkinter import PhotoImage
import matplotlib

thismanager = matplotlib.pyplot.get_current_fig_manager()
img = PhotoImage(file='filename.ppm')
thismanager.window.tk.call('wm', 'iconphoto', thismanager.window._w, img)

2

现在Qt5Agg后端已经成为主流,我在这里补充一下。它与Sijie Chen的答案中概述的Qt4Agg后端非常相似(几乎相同)。

import os
import matplotlib.pyplot as plt
from PyQt5 import QtGui

# Whatever string that leads to the directory of the icon including its name
PATH_TO_ICON = os.path.dirname(__file__) + '/static/icons/icon.ico'

plt.get_current_fig_manager().window.setWindowIcon(QtGui.QIcon(PATH_TO_ICON))

0

我发现在使用PyQT5的OS X下,执行plt.get_current_fig_manager().window.setWindowIcon()没有任何效果。要改变Dock图标,您必须在QApplication实例上调用setWindowIcon(),而不是在窗口上。

对我有效的方法是:

QApplication.instance().setWindowIcon(QtGui.QIcon(icon_path))

请注意,QApplication.instance() 在您实际创建图形之前将为None,因此请先执行该操作。

0
如果您正在使用Qt4Agg后端,则以下代码可能会对您有所帮助:
thismanager = plt.get_current_fig_manager()
from PyQt4 import QtGui
thismanager.window.setWindowIcon(QtGui.QIcon((os.path.join('res','shepherd.png'))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接