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

前端 未结 12 1491
一整个雨季
一整个雨季 2020-11-27 15:47

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:

from tk         


        
相关标签:
12条回答
  • 2020-11-27 16:02

    This works for me with Python3 on Linux:

    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'))
    
    0 讨论(0)
  • 2020-11-27 16:04

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

    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 .png it won't work cause it needs an .ico file. So you need to find converters to convert your icon from png to ico.

    0 讨论(0)
  • 2020-11-27 16:07

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

    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()
    
    0 讨论(0)
  • 2020-11-27 16:07

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

    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

    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]

    0 讨论(0)
  • 2020-11-27 16:08

    I recently ran into this problem and didn't find any of the answers very relevant so I decided to make a SO account for this.

    Solution 1: Convert your .ico File online there are a lot of site out there

    Solution 2: Convert .ico File in photoshop

    If you or your Editor just renamed your image file to *.ico then it is not going to work.
    If you see the image icon from your Windows/OS folder then it is working

    0 讨论(0)
  • 2020-11-27 16:11
    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.

    0 讨论(0)
提交回复
热议问题