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

前端 未结 12 1492
一整个雨季
一整个雨季 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:16
    #!/usr/bin/env python
    import tkinter as tk
    
    class AppName(tk.Frame):
        def __init__(self, master=None):
            tk.Frame.__init__(self, master)
            self.grid()
            self.createWidgets()
    
        def createWidgets(self):
            self.quitButton = tk.Button(self, text='Quit', command=self.quit)
            self.quitButton.grid()
    
    app = AppName()
    app.master.title('Title here ...!')
    app.master.iconbitmap('icon.ico')
    app.mainloop()
    

    it should work like this !

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

    Try this:

    from tkinter import *
    import os
    import sys
    
    root = Tk()
    root.iconbitmap(os.path.join(sys.path[0], '<your-ico-file>'))
    
    root.mainloop()
    

    Note: replace <your-ico-file> with the name of the ico file you are using otherwise it won't work.

    I have tried this in Python 3. It worked.

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

    So it looks like root.iconbitmap() only supports a fixed directory.
    sys.argv[0] returns the directory that the file was read from so a simple code would work to create a fixed directory.

    import sys
    def get_dir(src):
        dir = sys.argv[0]
        dir = dir.split('/')
        dir.pop(-1)
        dir = '/'.join(dir)
        dir = dir+'/'+src
        return dir
    

    This is the output

    >>> get_dir('test.txt')
    'C:/Users/Josua/Desktop/test.txt'
    

    EDIT:
    The only issue is that this method dosn't work on linux

    josua@raspberrypi:~ $ python
    Python 2.7.9 (default, Sep 17 2016, 20:26:04) [GCC 4.9.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import sys
    >>> sys.argv[0]
    ''
    >>>
    
    0 讨论(0)
  • 2020-11-27 16:19

    Make sure the .ico file isn't corrupted as well. I got the same error which went away when I tried a different .ico file.

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

    No way what is suggested here works - the error "bitmap xxx not defined" is ever present. And yes, I set the correct path to it.

    What it did work is this:

    imgicon = PhotoImage(file=os.path.join(sp,'myicon.gif'))
    root.tk.call('wm', 'iconphoto', root._w, imgicon)  
    

    where sp is the script path, and root the Tk root window.

    It's hard to understand how it does work (I shamelessly copied it from fedoraforums) but it works

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

    Got stuck on that too...

    Finally managed to set the icon i wanted using the following code:

    from tkinter import *
    root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='resources/icon.png'))
    
    0 讨论(0)
提交回复
热议问题