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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18537918/
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 10:59:03  来源:igfitidea点击:

Why isn't .ico file defined when setting window's icon?

pythonpython-3.xtkinterwindows-7tkinter.iconbitmap

提问by CrushedPixel

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:

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

from tkinter import *
root = Tk()

#some buttons, widgets, a lot of stuff

root.iconbitmap('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:

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

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

What I already did:

我已经做了什么:

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

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

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

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

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

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

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

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 py2exeor sthsolution.

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

采纳答案by CrushedPixel

You need to have favicon.icoin 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:

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

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

回答by Malek B.

#!/usr/bin/env python
import tkinter as tk

class AppName(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.quitButton = tk.Button(self, text='Quit', command=self.quit)
        self.quitButton.grid()

app = AppName()
app.master.title('Title here ...!')
app.master.iconbitmap('icon.ico')
app.mainloop()

it should work like this !

它应该像这样工作!

回答by Daniel

Make sure the .ico file isn't corrupted as well. I got the same error which went away when I tried a different .ico file.

确保 .ico 文件也没有损坏。当我尝试不同的 .ico 文件时,我遇到了同样的错误。

回答by alessandro

No way what is suggested here works - the error "bitmap xxx not defined" is ever present. And yes, I set the correct path to it.

此处建议的方法无效 - 错误“位图 xxx 未定义”一直存在。是的,我设置了正确的路径。

What it didwork is this:

所做的工作是这样的:

imgicon = PhotoImage(file=os.path.join(sp,'myicon.gif'))
root.tk.call('wm', 'iconphoto', root._w, imgicon)  

where spis the script path, and rootthe Tk root window.

sp脚本路径和rootTk 根窗口在哪里。

It's hard to understand how it does work (I shamelessly copied it from fedoraforums) but it works

很难理解它是如何工作的(我无耻地从fedoraforums复制了它)但它有效

回答by Josua Robson

So it looks like root.iconbitmap()only supports a fixed directory.
sys.argv[0]returns the directory that the file was read from so a simple code would work to create a fixed directory.

所以看起来root.iconbitmap()只支持固定目录。
sys.argv[0]返回读取文件的目录,因此一个简单的代码可以创建一个固定目录。

import sys
def get_dir(src):
    dir = sys.argv[0]
    dir = dir.split('/')
    dir.pop(-1)
    dir = '/'.join(dir)
    dir = dir+'/'+src
    return dir

This is the output

这是输出

>>> get_dir('test.txt')
'C:/Users/Josua/Desktop/test.txt'

EDIT:
The only issue is that this method dosn't work on linux

编辑:
唯一的问题是这种方法在 linux 上不起作用

josua@raspberrypi:~ $ python
Python 2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv[0]
''
>>>

回答by Steve Daulton

This works for me with Python3 on Linux:

这适用于 Linux 上的 Python3:

import tkinter as tk

# Create Tk window
root = tk.Tk()

# Add icon from GIF file where my GIF is called 'icon.gif' and
# is in the same directory as this .py file
root.tk.call('wm', 'iconphoto', root._w, tk.PhotoImage(file='icon.gif'))

回答by Er M S Dandyan

Both codes are working fine with me on python 3.7..... hope will work for u as well

这两个代码在 python 3.7 上对我来说都很好......希望也适用于你

import tkinter as tk
m=tk.Tk()
m.iconbitmap("myfavicon.ico")
m.title("SALAH Tutorials")
m.mainloop()

and do not forget to keep "myfavicon.ico" in the same folder where your project script file is present

并且不要忘记将“myfavicon.ico”保存在您的项目脚本文件所在的同一文件夹中

Another method

另一种方法

from tkinter import *
m=Tk()
m.iconbitmap("myfavicon.ico")
m.title("SALAH Tutorials")
m.mainloop()

[*NOTE:- python version-3 works with tkinter and below version-3 i.e version-2 works with Tkinter]

[*注意:- python 版本 3 与 tkinter 和低于版本 3 的工作,即版本 2 与 Tkinter 一起工作]

回答by afterm3

Got stuck on that too...

也卡在这...

Finally managed to set the icon i wanted using the following code:

最后设法使用以下代码设置了我想要的图标:

from tkinter import *
root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='resources/icon.png'))

回答by Tarun Kolla

from tkinter import *
from PIL import ImageTk, Image

Tk.call('wm', 'iconphoto', Tk._w, ImageTk.PhotoImage(Image.open('./resources/favicon.ico')))

The above worked for me.

以上对我有用。

回答by chan hoyin

I had the same problem too, but I found a solution.

我也遇到了同样的问题,但我找到了解决方案。

root.mainloop()

root.mainloop()

from tkinter import *

# must add
root = Tk()
root.title("Calculator")
root.iconbitmap(r"image/icon.ico")

root.mainloop()

In the example, what python needed is an icon file, so when you dowload an icon as .pngit won't work cause it needs an .icofile. So you need to find converters to convert your icon from pngto ico.

在这个例子中,python 需要的是一个图标文件,所以当你下载一个图标时,.png它不起作用,因为它需要一个.ico文件。所以,你需要找到转换器,你的图标从转换pngico