.ico 文件未在 Python Tkinter 中定义。

huangapple go评论85阅读模式
英文:

.ico file not defined in Python Tkinter

问题

所以我正在制作一个tkinter应用程序项目,但然后我遇到了这个错误。

Traceback (most recent call last):
File "c:\storage\program\py\binary drawer\main.py", line 166, in
root.iconbitmap("pencil.ico")
File "C:\Users\bhone\AppData\Local\Programs\Python\Python311\Lib\tkinter_init_.py", line 2136, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: 位图 "pencil.ico" 未定义


文件 "pencil.ico" 位于 C:\storage\program\py\binary drawer。名称正确,路径正确。
我该如何修复这个错误?

我正在使用 Python 3.11.3。
我正在使用 Windows 11。
英文:

So I was making a tkinter app project but then I came across this error.

Traceback (most recent call last):
  File "c:\storage\program\py\binary drawer\main.py", line 166, in <module>
    root.iconbitmap("pencil.ico")
  File "C:\Users\bhone\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 2136, in wm_iconbitmap
    return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: bitmap "pencil.ico" not defined

The file "pencil.ico" was in C:\storage\program\py\binary drawer. The name was right and the path was right.
How can I fix this error?

I'm using python 3.11.3.
I'm using Windows 11.

答案1

得分: 0

错误表示无法在当前工作目录中找到图标文件,该目录可能与脚本所在的目录不同。

如果要在脚本所在的目录中加载图标文件,您可以使用内部变量__file__构建图标文件的完整路径,如下所示:

from pathlib import Path

...

appdir = Path(__file__).parent    # 获取脚本所在的目录
iconfile = appdir / "pencil.ico"  # 构建图标文件的完整路径
root.iconbitmap(iconfile)
英文:

The error means that the ICON file cannot be found in current working directory which may not be the same directory where the script is.

If you want to load the ICON file in the same directory of the script, you can build the full path of the ICON file using internal variable __file__ as below:

from pathlib import Path

...

appdir = Path(__file__).parent    # get the directory where the script is
iconfile = appdir / "pencil.ico"  # build the full path of the ICON file
root.iconbitmap(iconfile)

huangapple
  • 本文由 发表于 2023年6月19日 20:03:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定