I am trying to use tkinter module to open a window to show a picture and was previously having trouble with: _tkinter.TclError: couldn't recognize data in image
I have since used the following this question to restructured my code to the following:
How do I insert a JPEG image into a python Tkinter window?
I have made a few changes to the code as I am using python 3.
When I have tried to execute the code: I get an error saying no file or directory exist. However i have used the following code to check:
python open() method IOError: [Errno 2] No such file or directory:
Below are the result of checking the files:
>>> os.listdir()
['comments.py', 'Conan.txt', 'conditions.py', 'dateandtime.py', 'desktop.ini', 'dictionaries.py', 'exceptions.py', 'forging_functions.py', 'formatting.py', 'graphics.py', 'Hello.py', 'leapdays.py', 'logging.py', 'loop.py', 'modules.py', 'months.py', 'numbers.py.py', 'Opening_files.py', 'Picture.jpg', 'print_hello.py.py', 'tkintercode1.py', 'tkintercode2.py', 'user_input.py', 'Writing_file.py', '__pycache__']
>>> os.getcwd()
'C:\\Users\\Draco\\OneDrive\\Documents\\Programming'
>>> os.chdir(r'C:\\Users\\Draco\\OneDrive\\Documents\\Programming')
>>> open('Picture.jpg')
<_io.TextIOWrapper name='Picture.jpg' mode='r' encoding='cp1252'>
Below is the code I am working with:
import tkinter as tk
from tkinter import *
window = tk.Tk()
window.title("Random Image")
window.geometry("300x300")
window.configure(background='grey')
path = "C:\Draco\OneDrive\Documents\Programming\Picture.jpg"
img = tkinter.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
window.mainloop()
Many thanks for any help
"C:\Draco\OneDrive\Documents\Programming\Picture.jpg" try path ="C:\\Draco\\OneDrive\\Documents\\Programming\\Picture.jpg" - double slash
EDIT
You have diff in paths. Users\Draco but in code just Draco
Related
I'm new to Python and I'm learning about Tkinter. I was trying to display an image:
from tkinter import *
from PIL import ImageTk,Image
img= ImageTk.PhotoImage(Image.open("flower.gif"))
lab = Canvas(image=img)
lab.pack()
mainloop()
But somehow it shows an error:
FileNotFoundError: [Errno 2] No such file or directory: 'flower.gif'
I already checked the name and the type of the file, and I'm sure that both of them are correct. Please help?
I found the answer to it, just in case there is anyone who has the same problem as me:
m=Tk()
img= ImageTk.PhotoImage(Image.open("C:/Users/VAIO/Downloads/flower.gif"))
lab = Label(image=img)
lab.pack()
mainloop()
I've used the following code:
# A Python program to display images in canvas
from tkinter import *
# create a root window
root = Tk()
# create a canvas as a child to the root window
c = Canvas(root,bg='black',height=700,width=1200)
# copy images into files
file1 = PhotoImage(file='PYTHON/Graphical User Interface[GUI]/Containers/cat.png')
file2 = PhotoImage(file='PYTHON/Graphical User Interface[GUI]/Containers/puppy.png')
# Display the Image in the canvas in NE direction
# when mouse is placed on cat image, we can see puppy image
id = c.create_image(500,200,ANCHOR=NE,image=file1,activeimage=file2)
# display some text below the image
id = c.create_text(500,500, text= "Displaying Image Demo in tkinter",\
font = ('Helvetica',30,'bold'), fill='blue')
# add canvas to the root
c.pack()
# wait for any events
root.mainloop()
When executed, the above code shows the following error in VScode:
Traceback (most recent call last):
File "/DATA/CodeTrainings/PYTHON/Graphical User Interface[GUI]/Containers/canvasImage(linux).py", line 12, in <module>
file2 = PhotoImage(file='PYTHON/Graphical User Interface[GUI]/Containers/puppy.png')
File "/home/lancelot/anaconda3/envs/pyTrain/lib/python3.8/tkinter/__init__.py", line 4061, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/home/lancelot/anaconda3/envs/pyTrain/lib/python3.8/tkinter/__init__.py", line 4006, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "PYTHON/Graphical User Interface[GUI]/Containers/puppy.png": no such file or directory
It says that any such file isn't present in the directory but it is indeed present:
And, everything works fine in windows, but when it comes to image files in LINUX an error always pops up!
Thanks if anyone could answer my question, but a detailed explanation or pointers on how to handle image files and what are the constraints while working with image files on LINUX is well appreciated.
Thank You!
Haha!
I have everything rightly setup, but the only thing where I went wrong is that, while downloading the files, I just renamed the file formats without actually converting them to the required image file format.
This was the problem that caused the error.
I used the online converters to convert the image and everything worked as it has to.
I've learned that renaming doesn't change the internal formatting in the files, therefore it is necessary to convert them using a converter into appropriate formats.
Please correct me if I'm wrong.
Thank You!
I have a tkinter file, that opens txt files and insert that into a Text widget.
I used cx_Freeze to build it to an .exe file, but if I right click and open the txt file with this program it does nothing.
Do anyone know, how van I do that my program automatically read the file, even if it's not opened form the program.
Sorry for my bad english, if I was not clear, I mean the "open the program from the txt file" that if you right-click the .txt file, there is an option "open with..." and I choose my .exe program made in tkinter.
This is my code:
from tkinter import *
import re
import os
from tkinter import filedialog
root = Tk()
def open_nd():
rawfile = filedialog.askopenfilename(title = "Select file",filetypes = (("Nonexistent documents","*.nd"), ("Exsistant decoded files","*.ed")))
print(rawfile)
file = open(rawfile, "r")
a = file.read()
area = Text(root)
area.pack()
area.insert(END, a)
menu=Menu(root)
root.config(menu=menu)
filebar=Menu(menu)
menu.add_command(label="Open", command=open_nd)
root.mainloop()
Again, sorry fo my bad english, and thanks the answers!
If i understood you right do these steps:
Right Click -> Open With
Click here More apps
Look for another program on this pc
Choose your exe here
I'm working on a data base with tkinter, i have been trying to add a background image to my interface but i get the error : "no such file or directory"
It's for a school project, i'm in aeronautical engineering but i'm pretty new to python.
This is the part of the code :
photo=PhotoImage(file="background.png")
zone_dessin = Canvas(Fsur, width=1000, height=600)
zone_dessin.create_image(250,250,image=photo)
zone_dessin.pack()
If the image is in the same folder of the script, then try:
script_path = os.path.dirname(os.path.realpath(__file__))
imagefile = os.path.join(script_path, 'background.png')
photo = PhotoImage(file=imagefile)
I am using python( my version is 2.7 ). I want to add an image to GUI (Tkinter) and then convert into executable format using pyinstaller.
I did followed as on SO, and also as said on ActiveState
When i mention the image's path on the code, it works only if i run it directly. If i convert it to exe it doesnt open.
Changing the code as mentioned from other solutions, like by converting it into encoded string, it runs fine on linux. But on windows it throws error
code:
from Tkinter import *
from PIL import ImageTk, Image
logo = '''
----- encoded string -----
'''
root = Tk()
logoimage = Tkinter.PhotoImage(master=root, data=logo)
Label(root, image=logoimage).pack()
root.mainloop()
Change 1:
The above code works on linux. On windows i get error on the line logoimage = Tkinter.PhotoImage(master=root, data=logo) as
NameError: name 'Tkinter' is not defined
Change 2:
So i tries changing the line as logoimage = ImageTk.PhotoImage(master=root, data=logo). The error i get is
File "C:\Python27\lib\site-packages\PIL\ImageTk.py", line 88, in __init__
image = Image.open(BytesIO(kw["data"]))
File "C:\Python27\lib\site-packages\PIL\Image.py", line 2330, in open
% (filename if filename else fp))
IOError: cannot identify image file <_io.BytesIO object at 0x00000000024BB150>
Exception AttributeError: "'PhotoImage' object has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <PIL.ImageTk.PhotoImage object at 0x00000000024D49E8>> ignored
Change 3:
But, if i change the line as iconImage= ImageTk.PhotoImage(Image.open('path_to_image.png')). It works only if i run directly. If i convert it to executable, then console opens for 2-3 seconds and displaying error something like Unable to locate the image file
Doing the decoding and converting explicitly may be more robust than what you're currently doing. This code works on Python 2.6.6 on Linux.
import io, base64
from Tkinter import *
from PIL import ImageTk, Image
#A simple 64x64 PNG fading from orange in the top left corner
# to red in the bottom right, encoded in base64
logo_b64 = '''
iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIA
AAAlC+aJAAAA/0lEQVR4nO3Zyw7CMAxEUdP//+W2rCqBoJA2noclS1kn9yjLeex7xKY76+
wNS+l6KSCjXgdIqhcB8uoVgNR6OiC7ngsA1BMBmHoWAFZPASDr8QBwPRiAr0cCKPUwAKse
AyDWAwDc+mwAvT4VoKjPA4jqkwC6+gyAtD7WSYC6fu4HDOonAB71dwE29bcATvXXAWb1Fw
F+9VcAlvXDANf6MYBx/QDAu/4fwL7+J6BC/TmgSP0JoE79N0Cp+g9Atfp3QMH6F0DN+gNQ
tj62WErXB2PgQNZLAb3U6wC91OsAvdTrAL3U6wC91OsAvdTrAL3U6wC91OsAvdTrAL3Uz7
z+BNmX4gqbppsaAAAAAElFTkSuQmCC
'''
#Decode the PNG data & "wrap" it into a file-like object
fh = io.BytesIO(base64.b64decode(logo_b64))
#Create a PIL image from the PNG data
img = Image.open(fh, mode='r')
#We must open the window before calling ImageTk.PhotoImage
root = Tk()
photo = ImageTk.PhotoImage(image=img)
Label(root, image=photo).pack()
Label(root, text='An embedded\nbase64-encoded PNG').pack()
root.mainloop()
For reference, here's what that embedded PNG looks like.
from Tkinter import *
#...
logoimage = Tkinter.PhotoImage(master=root, data=logo)
If you dump the Tkinter module straight into the global scope using import *, then you shouldn't prefix class and function names with the module name. Either remove the prefix, or remove the import *.
import Tkinter
#...
logoimage = Tkinter.PhotoImage(master=root, data=logo)
Or
from Tkinter import *
#...
logoimage = PhotoImage(master=root, data=logo)
I suspect you're not getting the error in Linux because your version of Python imports common modules automatically. Effectively, there's an invisible import Tkinter at the top of all your scripts.