OSError: cannot open resource - python

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.

Related

Tkinter: 'image ''pyimage2'' doesn't exist'?

My full code
from tkinter import *
i=0
for i in range(10) :
window = Tk()
window.title('add image')
window = Canvas(window,width= 600, height= 600)
window.pack()
image=PhotoImage(file=r"C:\\Users\\Konstantinos\\New folder\\hello.png")
window.create_image(0,0, anchor = NW, image=image)
window.mainloop()
The error when i run the program
File "C:\Programms\Lib\tkinter\__init__.py", line 2832, in _create
return self.tk.getint(self.tk.call(
^^^^^^^^^^^^^
_tkinter.TclError: image "pyimage2" doesn't exist
The error when i debug the program
Exception has occurred: TclError
image "pyimage2" doesn't exist
File "C:\Users\Konstantinos\New folder\demo.py", line 9, in <module>
window.create_image(0,0, anchor = NW, image=image)
So basically, the program opens an image multiple times. When th program is not in a loop it works but when i put it in a loop it gives me the error. Because i recently started programming i dont really know how to solve the problem and I have looked in other threads with the similar problem but none apply to me. I will appreciate any answer
The error probably comes from multiple Tk instances. Try removing the for-loop and then it will work. But if your intention was for multiple windows, then you can look into this answer: https://stackoverflow.com/a/36316105/9983213. Feel free to tinker around with the example.
A smaller example is:
import tkinter as tk
root = tk.Tk()
for i in range(5):
top = tk.Toplevel(root)
root.mainloop()

Why isn’t .ico file defined when setting window’s icon tkinter

I have this code, but why isn’t .ico file defined when setting window’s icon?
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("Tkinter App")
root.iconbitmap('C:\Users\User\Desktop\Main\yazilimfoto\Ataturk1.jpg')
root.mainloop()
there are some problems in your code
the icon you are setting is in .jpg format.
then use
ico = Image.open('test.jpg')
photo = ImageTk.PhotoImage(ico)
root.wm_iconphoto(False, photo)
and then
root.iconbitmap(photo)
and it will work. remember that you don't need to insert the entire file path (C:\Users\User\Desktop\Main\yazilimfoto\Ataturk1.jpg) but only the file path in your .py file directory

How to solve the following error in my python code, I'm trying to build a program using tiknter library

#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

Tkinter can't open image

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

Python PIL ImageTk.PhotoImage() is giving me a bus error?

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

Categories

Resources