Importing image into Tkinter - Python 3.5 - python

I'm majorly struggling to import an image into Tkinter for Python 3.5, this is for my A2 project and have hit a brick wall with every method of importing a .JPG file to my window. What I have below is my GUI layer for another window, based off another thread I found but didn't work at all. Any assistance appreciated.
import tkinter
from tkinter import *
root=Tk()
root.geometry('1000x700')
root.resizable(False, False)
root.title("Skyrim: After Alduin")
photo = PhotoImage(file="Skyrim_Map")
map=Label(root, image=photo)
map.photo=photo
map.pack()
root.mainloop()
Here's the error I receive:
Traceback (most recent call last):
File "E:\Programming\Text_Adventure_Project\GUI_Interface-S_AA.py", line 14, in <module>
photo = PhotoImage(file="Skyrim_Map")
File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3393, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3349, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "Skyrim_Map": no such file or directory

First check the path if with the correct path still persist the error "no such file or directory" please edit and put the newest version of your code.
If the error is "couldn't recognize data in image file" you can correct using PIL
[...]
from PIL import ImageTk
[...]
photo = ImageTk.PhotoImage(file='Skyrim_Map.jpg')
[...]

Try this:
from PIL import Image , ImageTk
img = Image.open("your_img")
image = ImageTk.PhotoImage(img)

An other point of view :
class Application:
...
self.photo=PhotoImage(file='picture.gif')
self.item=self.can.create_image(200, 100, image=self.photo)
...
Hope to help ! ;)

Related

Custom Tkinter Images

I'm trying to create a back button. I have an image called back-button.png in the folder img.
This is my code:
from tkinter import *
import customtkinter as ctk
root = Tk()
ctk.CTkLabel(root,
text = 'This is a label',
text_font =('Verdana', 17)).pack(side = LEFT, pady = 11)
img = PhotoImage(file="./img/back-button.png")
ctk.CTkButton(root, image = img).pack(side = LEFT)
root.mainloop()
When I run this code I get this error:
Traceback (most recent call last):
File "c:\Users\User\Desktop\youtube-audio-downloader\tempCodeRunnerFile.py", line 11, in <module>
ctk.CTkButton(root, image = img).pack(side = LEFT)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\customtkinter\customtkinter_button.py", line 102, in __init__
self.draw()
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\customtkinter\customtkinter_button.py", line 147, in draw
self.canvas.configure(bg=CTkColorManager.single_color(self.bg_color, self.appearance_mode))
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1646, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1636, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown color name "."
So, why is this happening? And how can I display an image on a button?
The problem is that the CtkButton widget doesn't not accept parameters the same way as standard widgets. The first parameter to a CtkButton is the background color, but you're passing the root window and the root window isn't a valid color.
You need to explicitly assign the root window to the master argument.
ctk.CTkButton(master=root, image = img).pack(side = LEFT)
# ^^^^^^^
You are getting error because you are using built-in image define method which is in Tkinter not in Customtkinter. Don't confuse these two. If you want to use Customtkinter only use that because when you are making bigger projects than this, it will be a whole mess if you use these two together.
import customtkinter
from PIL import Image, ImageTk
window = customtkinter.CTk()
button_image = customtkinter.CTkImage(Image.open("assets/yourimage.png"), size=(26, 26))
image_button = customtkinter.CTkButton(master=window, text="Text will be gone if you don't use compound attribute",image=button_image)
image_button.pack()
window.mainloop()

Images not showing up in tkinter GUI window

Basically I'm having trouble opening images (.jpg) in a tkinter GUI window.
I followed this tutorial: https://www.youtube.com/watch?v=lt78_05hHSk
But I just get a blank window.
from tkinter import *
root = Tk()
photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
# photo = PhotoImage(file="123k.jpg")
label = Label(root, image=photo)
label.pack()
root.mainloop()
The file path is correct and .jpg files are compatible with tkinter. What could be going on?
I get this error
Traceback (most recent call last):
File "C:\Users\xxx\ytrewq.py", line 5,
in <module> photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
File "C:\Users\xxxx\AppData\Local\Programs\Thonny\lib\tkinter_init_.py", line 3545,
in init Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\xxxx\AppData\Local\Programs\Thonny\lib\tkinter_init_.py", line 3501,
in init self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file
"C:\Users\xxxx\OneDrive\Desktop\123k.jpg"
This error occurs because only PhotoImage function can't recognize the .jpg formate image. For this, you could use png formate or you could use
Image.open(path_of_the_file) and then
ImageTk.PhotoImage(img_object)
for this Image and ImageTk you have to import this from PIL module
from PIL import Image, ImageTk
The hole solution code:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
# photo = PhotoImage(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
# photo = PhotoImage(file="123k.jpg")
img = Image.open(file=r"C:\Users\xxxx\OneDrive\Desktop\123k.jpg")
photo = ImageTk.PhotoImage(img)
label = Label(root, image=photo)
label.pack()
root.mainloop()

how can you filedialogbox to display a selected image in that specified window

i have tried this code to dispaly an image on a canvas by using open1 fuction call
....is this possible to do this....as every time i have tried ,it show given below errors
Errors
"C:\Program Files (x86)\Python37-32\python.exe" C:/Users/suhel/PycharmProjects/steography.py/main.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/suhel/PycharmProjects/steography.py/main.py", line 16, in open1
photo=PhotoImage(file=img)
File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 3545, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 3501, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "<_io.TextIOWrapper name='C:/Users/suhel/PycharmProjects/steography.py/rotated.png' mode='r' encoding='cp1252'>":
no such file or directory
THIS is my code
from tkinter import *
from tkinter.font import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import ImageTk
import cv2
import tkinter
from PIL import Image
from PIL import ImageTk
# **this is open fuction that allow to open a windows and
# select an image,i have tried to used used Canvas to display the image
# in the window,but it only display an empty window**
def open1():
img=filedialog.askopenfile(initialdir="/",title="select file",filetypes=(("image files",".png"),("all files","*py")))
r1=Tk()
canvas=Canvas(width=400,bg='blue')
photo=PhotoImage(file=img)
canvas.create_image(0,0,image=photo,anchor=NW)
canvas.pack()
r1.mainloop()
#main window
root=Tk()
#string var
ans1=StringVar
root.title(" Steganography")
label=Label(root,text="Image Based Steganography",anchor="center",fg="#7cd36b",bg="#000000")
label.pack()
f=Font(label,label.cget("font"))
f.config(family="Helvetica",size=15,weight="bold",underline=True)
label.configure(font=f)
entry=Entry(root,font=("Helvetica 16 bold italic"),insertwidth=4,width=50,textvariable=ans1)
entry.pack(padx=20, pady=20)
top=Frame(root)
choose=Button(top,text="Open",fg="#7cd36b",width=13,font=("Helvetica 10 bold italic"),bd=5,command=open1)
choose.grid(row=1,column=0,padx=6,pady=5)
get=Button(top,text="get",fg="#7cd36b",width=13,font=("Helvetica 10 bold italic"),bd=5)#,command=lambda:option())
get.grid(row=1,column=2)
top.configure(background="#000000")
top.pack()
root.configure(background="#000000")
root.geometry("350x400+400+400")
root.mainloop()

Getting PNGs to Python [duplicate]

I am using Tkinter to write a GUI and want to display a png file in a Tkiner.Label.
So I have some code like this:
self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
self.vcode.config(image=self.vcode.img)
This code runs correctly on my Linux machine. But when I run it on my windows machine, it fails. I also tested on several other machines (include windows and linux), it failed all the time.
The Traceback is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
SignupBox(self, self.server)
File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
self.refresh_vcode()
File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
self.vcode.img = PhotoImage(data=open('test.png').read(), format='png')
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: image format "png" is not supported
If I delete format='png' in the source code, the traceback will become:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
return self.func(*args)
File "C:\Documents and Settings\St\client\GUI.py", line 150, in showrbox
SignupBox(self, self.server)
File "C:\Documents and Settings\St\client\GUI.py", line 197, in __init__
self.refresh_vcode()
File "C:\Documents and Settings\St\client\GUI.py", line 203, in refresh_vcode
self.vcode.img = PhotoImage(data=open('test.png').read())
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3323, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 3279, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
TclError: couldn't recognize image data
So, what should I do to make it support png files?
PIL is now replaced by Pillow http://pillow.readthedocs.io/en/3.2.x/
solution:
from Tkinter import *
import PIL.Image
import PIL.ImageTk
root = Toplevel()
im = PIL.Image.open("photo.png")
photo = PIL.ImageTk.PhotoImage(im)
label = Label(root, image=photo)
label.image = photo # keep a reference!
label.pack()
root.mainloop()
If PIL could not be found in code, you do need a pillow install:
pip install pillow
tkinter only supports 3 file formats off the bat which are GIF, PGM, and PPM. You will either need to convert the files to .GIF then load them (Far easier, but as jonrsharpe said, nothing will work without converting the file first) or you can port your program to Python 2.7 and use the Python Imaging Library (PIL) and its tkinter extensions to use a PNG image.
A link that you might find useful: http://effbot.org/tkinterbook/photoimage.htm
Tkinter 8.6 supports png file format while tkinter 8.5 does not. If you have the option upgrade python and you should be fine to use png.
If you have to use an older version of python you should use Pillow (maintained pil fork) which also works on python3.
If you are starting a new project do not use python2 or PIL as suggested in the accepted answer, they are both depreciated technologies.
Fixed in official python.org 64-bit (only) installer for OS X. Tk version 8.6 is included out of the box. Warning: if you use homebrew, as of this post doing brew install python3 will only give you 8.5, and 8.6 is required to use png so you'll have to use official installer instead. To check which Tk you are using:
$ python3 -c 'import tkinter; print(tkinter.TkVersion);'
If it report 8.6, you are good to go.
from tkinter import *
from tkinter import messagebox
import os
from PIL import Image, ImageTk
root = Tk()
root.geometry("1300x720")
root.title("KEDİLERİMİZ ve KÖPEKLERİMİZ")
class Ana:
def __init__(self,name,roll):
self.name = name
self.roll = roll
resim = Label(root,width=77,height=43,bg="blue")
resim.place(x=730,y=10)
o = "1.PNG"
hu = o.find(".")
mu = o[hu:]
if mu == ".gif" or mu == ".png":
img = PhotoImage(file = o)
else:
photo = Image.open(o)
img = ImageTk.PhotoImage(photo)
resim.configure(image=img,width=img.width(),height=img.height())
resim.image = img
on windows you gotta use this specific format:
Example = PhotoImage(file='photo.png')
and if you wish to resize it to a smaller size:
Example = Example.subsample(2, 2)
or
Example = Example.subsample(3, 3)
Total Code:
Example = PhotoImage(file='photo.png')
Example = Example.subsample(1, 1)
but future warning, you gotta file the file location in with the photo unless you put the photo in the same file as the script!
try with PIL library instead of converting your image to GIF, PGM, or PPM (PhotoImage) only accept these 3 formats.
import tkinter as tk
import PIL.Image
import PIL.ImageTk
base = tk.Tk()
base.title("Dialy Dose")
logoPath = r"C:\Users\saigopi\Downloads\logo.png"
ref = PIL.Image.open(logoPath)
photo = PIL.ImageTk.PhotoImage(im)
inputEdit = tk.Label(base,text="Enter Quote")
save = tk.Button(base,text="Save",background="green",command=save())
logo = tk.Label(base,image=photo,text="Logo bro lite")
quote = tk.Label(base,text="I am saying you are more than something")
inputEdit.pack()
save.pack()
logo.pack()
quote.pack()
base.mainloop()
I used PhotoImage to add my Gui an icon with png format.
Like in below, It can work or give you an idea.
iconn = PhotoImage(file = "arcen.png" )
root.iconphoto(0, iconn)

Tkinter and PIL not loading jpegs

I'm trying to allow my Tkinter program to load and display .jpgs files from the standard .gif
import Image,ImageTk
root = Tk()
PILFile = Image.open("Image.jpg")
Image = PhotoImage(file=PILFile)
ImageLabel = Label(root,image=Image)
ImageLabel.image = Image
ImageLabel.pack()
root.mainloop()
The error message I get follows:
Traceback (most recent call last):
File "/home/paragon/Programs/Python/Web/MP3Tagger.py", line 25, in <module>
albumart = PhotoImage(file=PILfile)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 3271, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 3227, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "<JpegImagePlugin.JpegImageFile image mode=RGB size=1500x1500 at 0x98AEFCC>": no such file or directory
[Finished in 0.4s with exit code 1]
I am absouletly certain that the file exists in the correct format,what could I be doing wrong?
According to The Tkinter PhotoImage Class:
The PhotoImage class can read GIF and PGM/PPM images from files:
....
If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects:
from PIL import Image, ImageTk
image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
-> Replace Tkinter.PhotoImage with ImageTk.PhotoImage:
root = Tk()
PILFile = Image.open("Image.jpg")
Image = ImageTk.PhotoImage(PILFile) # <---
ImageLabel = Label(root, image=Image)
ImageLabel.image = Image
ImageLabel.pack()
root.mainloop()
Your error occurs because of the argument file:
Image = PhotoImage(file=PILFile)
This would specify a file path. In addition, you want ImageTk.PhotoImage. Instead, you want:
Image = ImageTk.PhotoImage(PILFile)

Categories