Linux 上的 Python 3.6 tkinter 窗口图标错误

San*_*eer 5 python linux tkinter python-3.x

我正在从《Python GUI 编程手册》学习 Python GUI。某项任务要求我通过将以下代码添加到我的配方中来更改窗口图标:

# Change the main windows icon
win.iconbitmap(r'C:\Python34\DLLs\pyc.ico')
Run Code Online (Sandbox Code Playgroud)

由于我使用的是 Linux,因此我必须将路径更改为/home/user/test.ico. 阅读类似的问题后,我知道这.ico仅适用于Windows。我尝试过.gif,但这也不起作用。我尝试过的现有SO文章: tkinter TclError:读取位图文件时出错 在我的python Tk基础应用程序中设置应用程序图标(在Ubuntu上) tkinter.TclError:图像“pyimage3”不存在

所有这三个都没有帮助。我收到以下每个错误:

In [3]: runfile('/home/bhedia/untitled1.py', wdir='/home/bhedia')
Traceback (most recent call last):

  File "<ipython-input-3-17a671578909>", line 1, in <module>
    runfile('/home/bhedia/untitled1.py', wdir='/home/bhedia')

  File "/home/bhedia/anaconda3/envs/mitx/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/home/bhedia/anaconda3/envs/mitx/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/bhedia/untitled1.py", line 58, in <module>
    img = tk.PhotoImage(file='test.ico')

  File "/home/bhedia/anaconda3/envs/mitx/lib/python3.5/tkinter/__init__.py", line 3403, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)

  File "/home/bhedia/anaconda3/envs/mitx/lib/python3.5/tkinter/__init__.py", line 3359, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)

TclError: couldn't recognize data in image file "test.ico"

In [4]: runfile('/home/bhedia/untitled1.py', wdir='/home/bhedia')
Traceback (most recent call last):

  File "<ipython-input-4-17a671578909>", line 1, in <module>
    runfile('/home/bhedia/untitled1.py', wdir='/home/bhedia')

  File "/home/bhedia/anaconda3/envs/mitx/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/home/bhedia/anaconda3/envs/mitx/lib/python3.5/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/bhedia/untitled1.py", line 59, in <module>
    root.tk.call('wm','iconphoto',root._w,img)

TclError: can't use "pyimage2" as iconphoto: not a photo image
Run Code Online (Sandbox Code Playgroud)

因此,我不确定在 Linux 上使用 Tkinter 库时如何更改窗口图标。

Abd*_*een 2

使用此代码:

10 icon = PhotoImage(file='yourfile.ico')   
20 root.tk.call('wm', 'iconphoto', root._w, icon)
Run Code Online (Sandbox Code Playgroud)

并确保yourfile.ico与 位于同一文件夹中yourfilename.py

巴基斯坦的和平