So I am running python 2.6 on a macbook pro and trying to write the code in python to display an image from a file in a label on a tkinter gui. The image is called image.png. The program runs without errors when I use this code
i = Image.open("image.png")
but when I do this code (I add one line):
i = Image.open("image.png")
photo = ImageTk.PhotoImage(i)
The program will crash and say "Bus error" in the command line. I don't even know what that means. I would think that PIL is installed correctly, since Image works, but the fact that ImageTk does not work puzzles me. Can anybody tell me what might be causing this Bus error?
EDIT:
Well I made a new program to test the error further. Here is the exact script I ran:
import Image
import ImageTk
i = Image.open("image.png")
photo = ImageTk.PhotoImage(i)
Now instead of getting "Bus error", this is my traceback.
Traceback (most recent call last):
File "imageTest.py", line 5, in <module>
photo = ImageTk.PhotoImage(i)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/ImageTk.py", line 113, in __init__
self.__photo = apply(Tkinter.PhotoImage, (), kw)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 3285, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 3226, in __init__
raise RuntimeError, 'Too early to create image'
RuntimeError: Too early to create image
Exception AttributeError: "PhotoImage instance has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <ImageTk.PhotoImage instance at 0x3c7a30>> ignored
I don't know about the Bus Error, but you need to create a Tk window before you can call PhotoImage. This script works for me-
import Image
import ImageTk
from Tkinter import Tk
window = Tk()
i = Image.open("image.png")
photo = ImageTk.PhotoImage(i)
ImageTk.PhotoImage has a garbage collection (ref count) bug in it. You must place a reference to the PhotoImage object in either a global variable of a class instance variable (e.g., self.myphoto = ImageTk.PhotoImage(i)).
See this warning:
http://infohost.nmt.edu/tcc/help/pubs/pil/image-tk.html
Even thought you do need to call a Tk window you also need to set the directory so that it can find the image.png.
import os
import Image
import ImageTk
from Tkinter import Tk
os.chdir('C:/../../') # put file path for the image.
window = Tk()
i = Image.open("image.png")
photo = ImageTk.PhotoImage(i)
window.mainloop()
Related
#the error
Traceback (most recent call last):
File "c:\Users\User\Desktop\assignment testing\week8\2810 lab\gui\gui1 (1).py", line 18, in
root.iconbitmap(r"c:/Users/User/Desktop/assignment testing/week8/2810 lab/gui")
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\tkinter_init_.py", line 2109, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
_tkinter.TclError: bitmap "c:/Users/User/Desktop/assignment testing/week8/2810 lab/gui" not defined
>
#The code
from tkinter import *
from tkinter import ttk
import tkinter as tk
from typing import Counter
from tkcalendar import Calendar, DateEntry
from PIL import ImageTk,Image
from tkinter import messagebox
import sqlite3;
#connect to databse
con = sqlite3.connect('Crash Statistics Victoria.db')
cur = con.cursor()
#root
root = Tk()
root.title('Accidents Analysis')
root.geometry("900x600")
root.iconbitmap(r"c:/Users/User/Desktop/assignment testing/week8/2810 lab/gui") //line 18
root.config(background = "#FFFFFF")```
I'm not that good but i'll try to answer hope it helps
remove the ```
root.config(background = "#FFFFFF")```
the image you are trying to upload might not be .ico you'll need to make sure its either 16x16, 32x32, 64x64 pixels, this might help although i'm not sure there are a lot online just google - https://convertio.co/jpg-ico/
root.iconbitmap(r"c:/Users/User/Desktop/assignment testing/week8/2810 lab/gui") //line 18
if this did not help then I have no clue, I had the same issue 2 days ago and it was because I didn't have a .ico icon so it could be different for you, hope this helps!
Your iconbitmap file extension should be .ico, .png or .jpeg
If problem still persists,
try adding root.update() at execution
for some reason, Tkinter can't open my image. If I don't add from tkinter import * it shows error message as:
Error Message without from tkinter import *:
C:\Users\NG>python e:/PythonTkinter/app.py
Traceback (most recent call last):
File "e:/PythonTkinter/app.py", line 12, in <module>
logo = Image.open('logo.png')
File "C:\Users\NG\anaconda3\lib\site-packages\PIL\Image.py", line 2891, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'logo.png'
and if I add from tkinter import * as shown below, it shows error message as shown below.
Code:
import tkinter as tk
import PyPDF2
from PIL import Image, ImageTk
from tkinter import *
# begaining of our UI window
root = tk.Tk()
canvas = tk.Canvas(root, width=600, height=300)
canvas.grid(columnspan=3)
# Adding logo
# logo = ImageTk.PhotoImage(Image.open("logo.png"))
logo = Image.open("logo.png")
logo = ImageTk.PhotoImage(logo)
logo_label = tk.Label(image=logo)
loogo_label.image = logo
logo_label.grid(column=1, row=0)
# ending of our UI window
root.mainloop()
Error Message with from tkinter import *:
C:\Users\NG>python e:/PythonTkinter/app.py
Traceback (most recent call last):
File "e:/PythonTkinter/app.py", line 14, in <module>
logo = Image.open("logo.png")
AttributeError: type object 'Image' has no attribute 'open'
Image is right there in same folder where this python file is.
WHAT AM I DOING WRONG ? HELP!
Explanation:-
You should probably understand what relative path is. When relative path is used, it is not relative the location of the python file, but instead the location from where you are running the python file. Here you are running the file from:
C:\Users\NG
But your python file and the image you are using is inside:
e:/PythonTkinter/app.py
Solution:-
So here either you can change the location from where you're running the code to the location with image file OR you can copy the image to the location you are running the py file from(i.e., 'C:\Users\NG').
And as far as the second error is concerned, it's never a good idea to say from x import *. When you import '*' from tkinter, it replaces the PIL.Image with tkinter.Image. And hence the error. So either remove that line or move it to the top most. Recommended import is:
import tkinter as tk
import PyPDF2
from PIL import Image, ImageTk
You are just using the first import here, so I don't see a point in using from tkinter import *, so just remove it.
You can simply do as follows
from tkinter import *
window = Tk() # instantiate an instance of a window for us
window.geometry("500x500")
#creating a photo image from png photo
icon = PhotoImage(file='GUI using Python\\flower.png')
window.iconphoto(True, icon)
window.mainloop()
starting from the comment (creating a photo image from png photo), you give a value in the file parameter the relative path not the full path, also take care of the backslash, you should write two backslashes and no need for all of these libraries that you are using unless you are counting on them for other tasks.
Your PIL import should be after 'from tkinter import *'. Also make sure to be in the same directory as the image
I am fairly new to python and very new to GUI's so please let me know if I have made an obvious mistake.
This is also my first post so please let me know if I need to edit my question in some way.
I don't understand why I am getting errors when trying to set an icon to a tkinter GUI.
I have already tried the following posts:
tkinter TclError: error reading bitmap file
https://www.delftstack.com/howto/python-tkinter/how-to-set-window-icon-in-tkinter/
There are other stack exhange posts on this topic but they are for windows and/or their OP's normally can get the icon to apear once then it doesn't work. This isn't my situation the programs fail to run. Though I have tried some of their suggestions as well.
I have tried three different ways of coding this:
Method 1:
from tkinter import *
import os
class MainWindow:
def __init__(self, master):
self.master = master
master.title('TD')
#self.iconbitmap(default = 'fist.ico')
root = Tk()
root.iconphoto(True, PhotoImage(os.path.join(os.getcwd(),'favicon-3.png')))
my_gui = MainWindow(root)
root.mainloop()
Result:
runfile('~./envs/thermTD_project/thermTD/untitled2.py', wdir='~./envs/thermTD_project/thermTD')
Traceback (most recent call last):
File "~./envs/thermTD_project/thermTD/untitled2.py", line 23, in <module>
root.iconphoto(True, PhotoImage(os.path.join(os.getcwd(),'favicon-3.png')))
File "/usr/lib/python3.8/tkinter/__init__.py", line 2116, in wm_iconphoto
self.tk.call('wm', 'iconphoto', self._w, "-default", *args)
TclError: can't use "~./envs/thermTD_project/thermTD/favicon-3.png" as iconphoto: not a photo image
File existence check:
In [42]: os.path.exists(os.path.join(os.getcwd(),'favicon-3.png'))
Out[42]: True
Method 2:
from tkinter import *
import os
class MainWindow:
def __init__(self, master):
self.master = master
master.title('TD')
#self.iconbitmap(default = 'fist.ico')
root = Tk()
root.iconbitmap(os.path.join(os.getcwd(),'favicon-3.ico'))
my_gui = MainWindow(root)
root.mainloop()
Result:
In [43]: runfile('~./envs/thermTD_project/thermTD/untitled2.py', wdir='~./envs/thermTD_project/thermTD')
Traceback (most recent call last):
File "~./envs/thermTD_project/thermTD/untitled2.py", line 22, in <module>
root.iconbitmap(os.path.join(os.getcwd(),'favicon-3.ico'))
File "/usr/lib/python3.8/tkinter/__init__.py", line 2071, in wm_iconbitmap
return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
TclError: bitmap "~./envs/thermTD_project/thermTD/favicon-3.ico" not defined
File existence check:
In [44]: os.path.exists(os.path.join(os.getcwd(),'favicon-3.ico'))
Out[44]: True
Method 3:
from tkinter import *
import os
class MainWindow:
def __init__(self, master):
self.master = master
master.title('TD')
#self.iconbitmap(default = 'fist.ico')
root = Tk()
img = PhotoImage(os.path.join(os.getcwd(),'favicon-3.ico'))
root.tk.call('wm','iconphoto', root._w, img)
my_gui = MainWindow(root)
root.mainloop()
Result:
In [45]: runfile('~./envs/thermTD_project/thermTD/untitled2.py', wdir='~./envs/thermTD_project/thermTD')
Traceback (most recent call last):
File "~./envs/thermTD_project/thermTD/untitled2.py", line 21, in <module>
root.tk.call('wm','iconphoto', root._w, img)
TclError: can't use "~./envs/thermTD_project/thermTD/favicon-3.ico" as iconphoto: not a photo image
File existence check:
See method 1
The code without any of the icon setting lines works as expected.
I have tried to gif, png and ico on each method. I am trying other file types now.
NB: While the filename is favicon actually they are ico, gif, png files of 64x64 pixles. Even the favicon ico only has 1 type of icon in it (if thats the right phrase). Its just I got them from a favicon which I converted to different formats using mogrify.
OS: Ubuntu 20.04.1 LTS
python 3.8.2
IDE: spyder 4.1.5
P.S. I would be gratefull to know what the syntax for including this in my init function. I am trying to do object orientated GUI's I am very much still learning.
import tkinter as tk
from tkinter import ttk,font
from PIL import Image,ImageDraw,ImageFont
root = tk.Tk()
def func_image():
image = Image.open(r'E:\side_300.png')
font_type_1 = ImageFont.truetype(str(combo.get()),18)
draw = ImageDraw.Draw(image)
draw.text((50,50),text='Hello',fill='red',font=font_type_1)
image.show()
fonts=list(font.families())
fonts.sort()
combo = ttk.Combobox(root,value=fonts)
combo.pack()
btn = ttk.Button(root,text='Click Me',command=func_image)
btn.pack()
root.mainloop()
Output
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py", line 1702, in __call__return self.func(*args)
File "test.py", line 9, in func_image
font_type_1 = ImageFont.truetype(str(combo.get()),18)
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 280, in truetype return FreeTypeFont(font, size, index, encoding, layout_engine)
File "C:\Users\Mevada\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageFont.py", line 145, in __init__layout_engine=layout_engine)
OSError: cannot open resource
Thanks...
import tkinter as tk
from tkinter import ttk
from PIL import Image,ImageDraw,ImageFont
import matplotlib.font_manager as fm
root = tk.Tk()
def func_image():
image = Image.open(r'E:\side_300.png')
font_type_1 = ImageFont.truetype(fm.findfont(fm.FontProperties(family=combo.get())),18)
draw = ImageDraw.Draw(image)
draw.text((50,50),text='Hello',fill='red',font=font_type_1)
image.show()
fonts = list(set([f.name for f in fm.fontManager.ttflist]))
fonts.sort()
combo = ttk.Combobox(root,value=fonts)
combo.pack()
btn = ttk.Button(root,text='Click Me',command=func_image)
btn.pack()
root.mainloop()
ImageFont.truetype requires that you give it a filename. You're not giving it a filename, you're giving it the name of a font family. Tkinter's font.families() does not return filenames.
It seems font cannot be found by PIL.
Find your font file in your computer. In windows, it always in C:\WINDOWS\Fonts directory. select one and modify your line 9 like it:
font_type_1 = ImageFont.truetype("bahnschrift.ttf",18)
bahnschrift.ttf is just a sample on my computer, I am not sure it exists on your computer.
It does not work because you have to insert the font filename as the first argument here: ImageFont.truetype(str(combo.get()),18).
If you try, for example, arial, you will succeed (if you have Arial installed on your computer, of course). Oh, and that function is case sensitive, so you have to write it in lowercase, because the filename is actually arial.ttf (you can drop the extension if want, by the way).
So, your combo box isn't working because when you choose a font named Courier New, for example, PIL won't find it, because its filename is cour.ttf. Unfortunately, you can't use that list of fonts from tkinter on ImageFont and I don't have a workaround for you in that case.
As I said, this might work, but you have to let go of your combo box: ImageFont.truetype('arial',18)
Before I go, one more important note: if you are working on a OS other than Windows, you have to type the full path to the font file.
I'm currently trying to create a Python3 Tkinter program which I can launch by double clicking or opening from other python scripts, instead of going through idle.
So far I've had little luck, as when I attempt to launch the script the console opens for a moment and then crashes.
EDIT: Removing the logo segment of code allows the program to run. Any ideas why and how to fix it? Also I have not had to run a program via the console before so little luck there.
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Kinematics")
Logo_frame = LabelFrame(root, bg = "white")
Logo_frame.grid(row=0, column=12, sticky = "NSEW")
#Logo
Logo = Image(file="Logo-S.gif")
image_label = ttk.Label(Logo_frame, image=Logo)
image_label.grid(row=0, column=0, rowspan = 3)
root.mainloop()
The error from your present code is:
Exception ignored in: <bound method Image.__del__ of <tkinter.Image object at 0x7f1aa91df2e8>>
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 3357, in __del__
if self.name:
AttributeError: 'Image' object has no attribute 'name'
Traceback (most recent call last):
File "/home/sunbear/Coding/python35/tkinter/stackoverflow_questions/test52.py", line 22, in <module>
Logo = Image(file="Logo-S.gif")
TypeError: __init__() missing 1 required positional argument: 'imgtype'
There is a typo in your command in line 22(your original code before edit). You need the following correction to overcome this error, i.e.:
#Logo
#Logo = Image(file="Logo-S.gif")
Logo = PhotoImage(file="Logo-S.gif") #you should change to this.
You can read more about when to use PhotoImage and Image using this link I gave you.
I just attempted to run the program with a random gif I found online, all seemed to work to plan. I'm running windows 10 pro... maybe try re-saving/downloading the gif.