Search code examples
pythontkinterttk

Python: Tkinter iconbitmap assignment only works at module level


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


Solution

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