为什么设置窗口图标时没有定义 .ico 文件?

问题描述

当我尝试使用下面的代码将左上角的窗口图标从难看的红色TK"更改为我自己的 favicon 时,Python 抛出了一个错误:

When I tried to change the window icon in the top left corner from the ugly red "TK" to my own favicon using the code below, Python threw an error:

from tkinter import *
root = Tk()

#some buttons, widgets, a lot of stuff

root.iconbitmap('favicon.ico')

这应该将图标设置为favicon.ico"(根据网络上的许多论坛帖子).但不幸的是,这一行所做的只是抛出以下错误:

This should set the icon to 'favicon.ico' (according to a lot of forum posts all over the web). But unfortunately, all this line does is throw the following error:

Traceback (most recent call last):
  File "d:ladvclientmainapp.py", line 85, in <module>
    root.iconbitmap(bitmap='favicon.ico')
  File "C:Python33lib	kinter\__init__.py", line 1637, in wm_iconbitmap
    return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "favicon.ico" not defined

我已经做了什么:

  • 我检查了路径 - 一切都 100% 正确
  • 我尝试了其他文件格式,例如 .png.bmp - 都没有成功
  • 我在很多网站上都查过这个问题
  • I checked the path - everything is 100% correct
  • I tried other file formats like .png or .bmp - none worked
  • I looked this problem up on many websites

第三点,我最喜欢的关于 Tkinter 的网站 effbot.org 告诉我,Windows 忽略了 iconbitmap 功能.但这并不能解释为什么会抛出错误!

And for the third point, effbot.org, my favorite site about Tkinter, told me that Windows ignores the iconbitmap function. But this doesn't explain why it throws an error!

有一些hackish"方法可以避免这个问题,但它们都不是为 Python 3.x 编写的.

There are some "hackish" ways to avoid that issue, but none of them are Written for Python 3.x.

所以我的最后一个问题是:有没有办法使用 Python 3.x 和 Tkinter 获得自定义图标?

So my final question is: Is there a way to get a custom icon using Python 3.x and Tkinter?

另外,不要告诉我应该使用另一个 GUI 库.我希望我的程序可以在每个平台上运行.我还想要一个编码版本,而不是 py2exesth 解决方案.

Also, don't tell me I should use another GUI Library. I want my program to work on every platform. I also want a coded version, not a py2exe or sth solution.


解决方案

您需要将 favicon.ico 与您的脚本放在同一个文件夹或字典中,因为 python 只在当前字典中搜索或者您可以输入完整的路径名.例如,这有效:

You need to have favicon.ico in the same folder or dictionary as your script because python only searches in the current dictionary or you could put in the full pathname. For example, this works:

from tkinter import *
root = Tk()

root.iconbitmap(r'c:Python32DLLspy.ico')
root.mainloop()

但这会导致您出现同样的错误:

But this blows up with your same error:

from tkinter import *
root = Tk()

root.iconbitmap('py.ico')
root.mainloop()

相关文章