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 tkinter import *
root = Tk()
#some buttons, widgets, a lot of stuff
root.iconbitmap('favicon.ico')
This should set the icon to 'favicon.ico' (according to a lot of forum posts all over the web). But unfortunately, all this line does is throw the following error:
Traceback (most recent call last):
File "d:\ladvclient\mainapp.py", line 85, in <module>
root.iconbitmap(bitmap='favicon.ico')
File "C:\Python33\lib\tkinter\__init__.py", line 1637, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "favicon.ico" not defined
What I already did:
I checked the path - everything is 100% correct
I tried other file formats like .png or .bmp - none worked
I looked this problem up on many websites
And for the third point, effbot.org, my favorite site about Tkinter, told me that Windows ignores the iconbitmap function.
But this doesn't explain why it throws an error!
There are some "hackish" ways to avoid that issue, but none of them are Written for Python 3.x.
So my final question is: Is there a way to get a custom icon using Python 3.x and Tkinter?
Also, don't tell me I should use another GUI Library. I want my program to work on every platform. I also want a coded version, not a py2exe or sth solution.
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()
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
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'))
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'))
#!/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 !
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.
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]
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.
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.
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]
''
>>>
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.
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
I'm using Visual Studio Code. To make "favicon.ico" work, you need to specify in which folder you are working.
You press ctrl + shift + p to open the terminal cmd+shift+p on OSX.
In the terminal, you type: cd + the path where you are working. For example: cd C:\User\Desktop\MyProject
CONVERT YOUR IMAGE FILE INTO A PHOTO IMAGE FIRST
img = PhotoImage(file='your-icon')
Related
I keep getting the error, TclError: image "pyimage8" doesn't exist.
It is strange, as the number increases every time I run it?
I'm running python using spyder, dunno whether this affects anything.
Here is my code:
#import tkinter
import Tkinter as tk
homescreenImage = PhotoImage(file="Homescreen.gif")
#create a GUI window.
root = Tk()
#set the title.
root.title("Welcome to the Pit!")
#set the size.
root.geometry("1100x700")
homescreenFrame = tk.Frame(root, width=1100, height = 700)
homescreenFrame.pack()
homescreenLabel = tk.Label(homescreenFrame, image=homescreenImage)
homescreenLabel.pack()
#start the GUI
root.mainloop()
I found that my script would run once and then give me an error on subsequent runs. If I restarted the console, it would run again. I solved the problem by using the following code in the beginning of my script:
import sys
if "Tkinter" not in sys.modules:
from Tkinter import *
It works every time now.
If you import Tkinter as tk you should use the alias tk when calling tk, eg. root = tk.Tk(). Otherwise Python will not find Tk.
You don't need to import PIL for this.
You can not create a Photoimage before you create Tk.
Try this:
import Tkinter as tk
root = tk.Tk()
root.title("Welcome to the Pit!")
root.geometry("1100x700")
homescreenImage = tk.PhotoImage(file="Homescreen.gif")
homescreenFrame = tk.Frame(root, width=1100, height = 700,)
homescreenFrame.pack()
homescreenLabel = tk.Label(homescreenFrame, image=homescreenImage)
homescreenLabel.pack()
root.mainloop()
Be kind and paste the whole error message in your question also.
Following could be the errors:
1) Give the whole path to the file name
eg: "/home/user/Homescreen.gif"
2) If you are using windows and the above doesn't work:
use "\\C:\\home\\Homescreen.gif" (this is because, windows gets confused)
3) If that also, doesn't work, ensure that the directory of your python
program is the same as that of the image.
4) Also, create the photoimage only after you have created the root
window.
5) For some reason, while running in the debugger, if any previous
executions had thrown errors I get the "pyimage doesn't exist" error.
However, if I restart the debugger (or no previously executed scripts
have thrown errors), then the program runs fine.
6) Also, don't import PIL, it's not required.
Try all the above, if it doesn't work let me know.
Hope this helps.
i think this could be due to :
tkinter only supports .png format for images
Yet, there are other ways to add .gif`` instead of PhotoImage```
In my case, it was because I forgot to keep a reference to the image. Try adding this line after creating the label:
homescreenLabel.image=homescreenImage.
You should use Toplevel window that is directly managed by the window manager.
Just change :
root = Tk() to root = Toplevel()
I am trying to set an application icon (python3 / tkinter) like this:
Interface()
root.title("Quicklist Editor")
root.iconbitmap('#/home/jacob/.icons/qle_icon.ico')
root.resizable(0, 0)
root.mainloop()
no matter what I do, I keep getting an error message (Idle), saying:
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: error reading bitmap file "/home/jacob/.icons/qle_icon.ico"
What am I doing wrong?
The problem is not the code, but the icon. I tried creating an xbm with another program than Gimp (some KDE icon editor), and although it looks terrifyingly ugly, it does show an icon.
I guess I have to find a creator that gives an "understandable" icon for my Python program.
Edit
The iconbitmap method turned out to be black and white only, so it was useless after all.
After a long search, I found the solution to set the color of an application's icon for Python 3 (on Linux). I found it here:
root = Tk()
img = PhotoImage(file='your-icon')
root.tk.call('wm', 'iconphoto', root._w, img)
This is an old question, and there is lots of stuff written about it on the web, but all of it is either incorrect or incomplete, so having gotten it to work I thought it would be good to record my actual working code here.
First, you'll need to create an icon and save it in two formats: Windows "ico" and Unix "xbm". 64 x 64 is a good size. XBM is a 1-bit format--pixels just on or off, so no colors, no grays. Linux implementations of tkinter only accept XBM even though every Linux desktop supports real icons, so you're just out of luck there. Also, the XBM spec is ambiguous about whether "on" bits represent black or white, so you may have to invert the XBM for some desktops. Gimp is good for creating these.
Then to put the icon in your titlebar, use this code (Python 3):
import os
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("My Application")
if "nt" == os.name:
root.wm_iconbitmap(bitmap = "myicon.ico")
else:
root.wm_iconbitmap(bitmap = "#myicon.xbm")
root.mainloop()
This will allow you to use PNG files as icons, and it does render color. I tested it on Xubuntu 14.04, 32-bit with Python 3.4 (root is your Tk object):
import sys, os
program_directory=sys.path[0]
root.iconphoto(True, PhotoImage(file=os.path.join(program_directory, "test.png")))
(Finding program directory is important if you want it to search for test.png in the same location in all contexts. os.path.join is a cross-platform way to add test.png onto the program directory.)
If you change True to False then it won't use the same icon for windows that aren't the main one.
Please let me know if this works on Windows and Mac.
I tried this, and I couldn't get it to work using Windows 7.
Found a fix.
Use Jacob's answer, but the file has to be a .gif if you're using my OS, (Windows 7) it appears.
Make a 64x64 gif using MS paint, save it, use the file path and bingo, works.
I hope this helps you for cross-platform ability
LOGO_PATH="pic/logo.ico"
LOGO_LINUX_PATH="#pic/logo_1.xbm" #do not forget "#" symbol and .xbm format for Ubuntu
root = Tk()
if detect_screen_size().detect_os()=="Linux":
root.iconbitmap(LOGO_LINUX_PATH)
else:
root.iconbitmap(LOGO_PATH)
Simply using an r string to convert the directory into raw text worked for me:
ex:
app.iconbitmap(r'enter your path here')
In my case, Ubuntu 20.04, python 3.6 (conda), the command iconbitmap(bitmap=icon_path) failed w/ this error. In the end, I put the command w/in a try-except block and it worked; I can see the colorful image.
I'm surprised to see this is such an old question with no good answers, not in eight years! I too want my own icon for my "quickie" tkinter program.
What does work for me on Linux and Python3:
#!/usr/bin/env python
import tkinter
from PIL import Image, ImageTk
root = tkinter.Tk()
im = Image.open('junk.png')
photo = ImageTk.PhotoImage(im)
root.wm_iconphoto(True, photo)
root.mainloop()
The key seems to be using Image and ImageTk. I found zero solutions that worked without these.
[1]
The code is:
import Tkinter
from Tkinter import *
# Create Tk instance
root = Tkinter.Tk(className="test")
# Open Notepad
def openNotepad():
import pywinauto
app = pywinauto.Application.start("notepad.exe")
# Add menu
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="01 File", menu=filemenu)
filemenu.add_command(label="New", command=openNotepad)
# Pack all
root.mainloop()
[2]
The code works if I double click on .py file.
If I leave only the openNotepad() function, then .exe will work.
According to docs: https://github.com/pyinstaller/pyinstaller/wiki/Supported-Packages, the pywinauto library is supported.
If I leave only the Tkinter snippet, the .exe will work.
Therefore please share what I am doing wrong or please suggest other python installer for python 2.7x.
By commenting out the line starting with: excludedimports in files \PyInstaller\hooks\hook-PIL.py and hook-PIL.SpiderImagePlugin.py, the problem was solved.
Try to replace every exit(), quit(), or os._exit() with sys.exit().
I see that you don't have any of these in your code but somebody else might find this advice to be useful.
My versions: python3.4, pyinstaller3.1.1
Well I have this:
import tkinter
gui = tkinter.Tk()
gui.iconbitmap(default='/home/me/PycharmProjects/program/icon.ico')
gui.mainloop()`
But when I run I get an error saying
Traceback (most recent call last):
File "/home/spencer/PycharmProjects/xMinecraft/GUI.py", line 17, in <module>
gui.iconbitmap(default='/home/me/PycharmProjects/program/icon.ico')
File "/usr/lib/python3.3/tkinter/__init__.py", line 1638, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, '-default', default)
_tkinter.TclError: wrong # args: should be "wm iconbitmap window ?bitmap?"`
I'm trying to use tkinter to set a window I've made's icon. I'm using Pycharm installed on ubuntu 13.10. I've tried various things from changing '/' to '\' and adding a Z:// to the front because that's my partition's name. But I still get the error so please help.
You need to either specify the path as the first positional argument, or use the keyword argument "bitmap". It's rather poorly documented, but the bitmap argument is required; you can't just give the default keyword argument. In fact, the bitmap keyword argument has been removed in python 3.
However, you can only use .ico files on windows. On ubuntu and other linux boxes you need to use a .xbm file, and need to prefix it with "#"
This should work on windows only:
gui.iconbitmap('/home/me/PycharmProjects/program/icon.ico')
On ubuntu, it would need to be something like this:
gui.iconbitmap('#/home/me/PyCharmProjets/program/icon.xbm')
You can't just rename a .ico file to .xbm, they are completely different file formats.
Interesting bit of research
png, svg, ico didn't work
I found one xbm on my machine (xubuntu - Linux dist) , thanks to sqlitemanager
tool.xbm
note the # - the code is a modification of Lutz "Programming Python" Chapter 1, tkinter103.py
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title='Reply', message='Hello %s!' % name)
top = Tk()
#img = PhotoImage(file='py-blue-trans-out.ico') #no
top.title('Echo')
top.iconbitmap('#tool.xbm') #yes
#top.iconphoto(True, PhotoImage(file='tool.xbm')) #no
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.pack(side=TOP)
btn = Button(top, text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
Still in 2018 a high Rank google question.
what works for me in python3
is to use ico in Windows and gif in Linux :
if ( sys.platform.startswith('win')):
gui.iconbitmap('logo_Wicon.ico')
else:
logo = PhotoImage(file='logo.gif')
gui.call('wm', 'iconphoto', gui._w, logo)
There are two ways,
1) use xbm file in ubuntu as ubuntu will not able to read ico files. but issue here is xbm can display only black and white images.
2) use tkinter.photoimage to display icon image like below,
img = PhotoImage(file='your-icon')
root.tk.call('wm', 'iconphoto', root._w, img)
issue here is photoimage can read only GIF and PGM/PPM images.
see details here - https://stackoverflow.com/a/11180300
To display colored icons in linux you need to do it as shown below:
import tkinter
window = tkinter.Tk()
window.title("My Application")
img = tkinter.PhotoImage(file='~/pharmapos/pharmapos.png')
window.tk.call('wm', 'iconphoto', window._w, img)
window.mainloop()
I had to convert to an XBM format and use the following root.iconbitmap('#imagename.xbm') however my platform is Ubuntu and I discovered my os theme has no spot for he image....
this worked for me in linux mint:
from tkinter import *
from PIL import Image, ImageTk
main_fn=Tk()
log= Image.open("path_to_image.ico")
logo = ImageTk.PhotoImage(log)
main_fn.tk.call('wm', 'iconphoto', main_fn._w, logo)
main_fn.mainloop()
We can use iconphoto on linux. Colored icon works well too. You can use .png files. The .ico file can be converted using 'convert' utility.
convert icon.ico icon.png
First create a PhotoImage widget:
icon = tkinter.PhotoImage(file='icon.png')
Then use iconphoto to change the icon:
root = Tk()
root.iconphoto(False, icon)
Reference: Please have a look at this link
import tkinter
gui = tkinter.Tk()
gui.iconbitmap()
gui.mainloop()
In place of gui.iconbitmap(default='/home/me/PycharmProjects/program/icon.ico') i used gui.iconbitmap() this just works for me.
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 tkinter import *
root = Tk()
#some buttons, widgets, a lot of stuff
root.iconbitmap('favicon.ico')
This should set the icon to 'favicon.ico' (according to a lot of forum posts all over the web). But unfortunately, all this line does is throw the following error:
Traceback (most recent call last):
File "d:\ladvclient\mainapp.py", line 85, in <module>
root.iconbitmap(bitmap='favicon.ico')
File "C:\Python33\lib\tkinter\__init__.py", line 1637, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "favicon.ico" not defined
What I already did:
I checked the path - everything is 100% correct
I tried other file formats like .png or .bmp - none worked
I looked this problem up on many websites
And for the third point, effbot.org, my favorite site about Tkinter, told me that Windows ignores the iconbitmap function.
But this doesn't explain why it throws an error!
There are some "hackish" ways to avoid that issue, but none of them are Written for Python 3.x.
So my final question is: Is there a way to get a custom icon using Python 3.x and Tkinter?
Also, don't tell me I should use another GUI Library. I want my program to work on every platform. I also want a coded version, not a py2exe or sth solution.
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()
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
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'))
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'))
#!/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 !
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.
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]
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.
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.
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]
''
>>>
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.
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
I'm using Visual Studio Code. To make "favicon.ico" work, you need to specify in which folder you are working.
You press ctrl + shift + p to open the terminal cmd+shift+p on OSX.
In the terminal, you type: cd + the path where you are working. For example: cd C:\User\Desktop\MyProject
CONVERT YOUR IMAGE FILE INTO A PHOTO IMAGE FIRST
img = PhotoImage(file='your-icon')