为什么在设置窗口图标时没有定义 .ico 文件? [英] Why isn't .ico file defined when setting window's icon?

查看:121
本文介绍了为什么在设置窗口图标时没有定义 .ico 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用下面的代码将左上角的窗口图标从丑陋的红色TK"更改为我自己的图标时,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:\ladvclient\mainapp.py", line 85, in <module>
    root.iconbitmap(bitmap='favicon.ico')
  File "C:\Python33\lib\tkinter\__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 - 没有效果
  • 我在很多网站上都查过这个问题

关于第三点,我最喜欢的关于 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:\Python32\DLLs\py.ico')
root.mainloop()

但这会因您的相同错误而崩溃:

But this blows up with your same error:

from tkinter import *
root = Tk()

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

这篇关于为什么在设置窗口图标时没有定义 .ico 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆