Python: Tkinter iconbitmap assignment only works at module level

我们两清 提交于 2019-12-08 09:36:59

问题


I'm using a tkinter.ttk window and I'm using an icon to set the iconbitmap of my window. However root.iconbitmap() is ignored on Windows 10. But There is an easy way to avoid an error: root.tkinter.call('wm', 'iconphoto', root._w, icon)

So:

from tkinter import *
from tkinter.ttk import *

root=Tk()
root.call('wm', 'iconphoto', root._w, icon)

works. BUT:

def func():
    root=Tk()
    root.call('wm', 'iconphoto', root._w, icon)

does NOT work. An error occurs. It's interesting that that error is exactly the same one that occurs when you use root.iconbitmap():

Traceback (most recent call last):
File "E:\test.py", line 95, in <module>
func()
File "E:\test.py", line 36, in func
t.call('wm', 'iconphoto', t._w, icon)
_tkinter.TclError: can't use "pyimagex" as iconphoto: not a photo Image

And there is one interesting fact left: In another file I tried to use it as a function too, it worked. In the new file (test.py) it didn't work (and it was the same function). Does anybody know why it doesn't work and what I can do to avoid an error? Thanks in advance...


回答1:


If you've a window opened already and wants to open another one with it's own icon then you should use Toplevel() instead of Tk() and to change the icon use

W2 = Toplevel()
icon = PhotoImage(file='icon.png')
W2.tk.call('wm', 'iconphoto', root._w, icon)

Example:

from tkinter import *
from tkinter.ttk import *

def test():
    root = Toplevel()
    icon = PhotoImage( file='icon.png' )  # path to the icon
    root.tk.call('wm', 'iconphoto', root._w, icon)

r = Tk()

b =  Button(r, text='press', command=test)
b.pack()

mainloop()


来源:https://stackoverflow.com/questions/55769961/python-tkinter-iconbitmap-assignment-only-works-at-module-level

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!