Display image in tkinter - python

I don't know why this code is not displaying any image when I run it.
from tkinter import *
import os
root = Tk()
images = os.listdir()
i = 0
for images in images:
if images.endswith(".png"):
photo = PhotoImage(file=images)
label = Label(image=photo)
label.pack()
print("reached here")
root.mainloop()

So basically you need to have PIL installed
pip install PIL
then
from tkinter import *
import os
from PIL import Image, ImageTk
root = Tk()
images = os.listdir()
imglist = [x for x in images if x.lower().endswith(".jpg")]
for index, image in enumerate(imglist): #looping through the imagelist
photo_file = Image.open(image)
photo_file = photo_file.resize((150, 150),Image.ANTIALIAS) #resizing the image
photo = ImageTk.PhotoImage(photo_file) #creating an image instance
label = Label(image=photo)
label.image = photo
label.grid(row=0, column=index) #giving different column value over each iteration
print("reached here with "+image)
root.mainloop()
If you want to use pack() manager, then change
for image in imglist:
....... #same code as before but grid() to
label.pack()
Do let me know if any errors or doubts
Cheers

I played a little and got some results. You can refine it:
from tkinter import *
import os
root = Tk()
images = os.listdir()
imglist = [x for x in images if x.lower().endswith(".png")]
i = 0
photolist = []
labellist= []
for image in imglist:
photo = PhotoImage(file=image)
photolist.append(photo)
label = Label(image=photo)
labellist.append(label)
label.pack()
print("reached here with "+image)
root.mainloop()

Related

How to get the image name of a label in python tkinter?

Suppose I have below codes:
import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
my_img = ImageTk.PhotoImage(Image.open("./Images/img.jpg"))
my_img1 = ImageTk.PhotoImage(Image.open("./Images/img1.jpg"))
my_img2 = ImageTk.PhotoImage(Image.open("./Images/img2.jpg"))
image_list = [my_img, my_img1, my_img2]
label1 = tk.Label(root, image=image_list[0])
print(label1.cget('image'))
I want to get the name of the image that is currently assigned to label1, in this example, the result I want to get is "my_img", how to do it? Thank you.

how do you make a randomized photo slide show in python

I am trying to make a randomized slideshow in Python
current working code:
import tkinter as tk
from itertools import cycle
from PIL import ImageTk, Image
with open('list.txt', 'r') as f:
lines = f.read().strip('[]')
images = [i.strip("\" ") for i in lines.split(',')]
photos = cycle(ImageTk.PhotoImage(Image.open(image)) for image in images)
def slideShow():
img = next(photos)
displayCanvas.config(image=img)
root.after(1200, slideShow)
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
root.geometry('%dx%d' % (1920, 1280))
displayCanvas = tk.Label(root)
displayCanvas.pack()
root.after(1000, lambda: slideShow())
root.mainloop()
I tried randomizing it by changing img = next(photos) to img = random.choice(photos)
I got the error NameError: name 'random' is not defined
full randomized code:
import tkinter as tk
from itertools import cycle
from PIL import ImageTk, Image
import random
with open('list.txt', 'r') as f:
lines = f.read().strip('[]')
images = [i.strip("\" ") for i in lines.split(',')]
photos = cycle(ImageTk.PhotoImage(Image.open(image)) for image in images)
def slideShow():
img = random.choice(photos)
displayCanvas.config(image=img)
root.after(1200, slideShow)
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
root.geometry('%dx%d' % (1920, 1280))
displayCanvas = tk.Label(root)
displayCanvas.pack()
root.after(1000, lambda: slideShow())
root.mainloop()
How should I go about properly converting my slide show to a random one?
I would just use shuffle() from random which is part of the Python standard library.
import random
random.shuffle(images)
Just keep in mind that shuffle works in place and returns None

unable to update image in tkinter using a function

I am trying to create a Tkinter to make a window that shows images using a label, then update the image using an update function, but the image that I am trying to show doesn't show up in the Tkinter window, instead, a black screen appears
I have two working code
one that shows an image on the Tkinter window
one what loops a GIF using an update function
I tried to combine them
the code I am working on that doesn't work
#import GUI
from tkinter import *
#change dir
import os
os.chdir("C:/Users/user/Desktop/test image folder/")
#add delay
import time
#import image
from PIL import Image, ImageTk
#set up the window
window = Tk()
#window.title("modify images")
#list of filename
filelist = []
#loop over all files in the working directory
for filename in os.listdir("."):
if not (filename.endswith('.png') or filename.endswith('.jpg')):
continue #skip non-image files and the logo file itself
filelist = filelist + [filename]
#list of filename
print(filelist)
#show first pic
imagefile = filelist[0]
photo = ImageTk.PhotoImage(Image.open(imagefile))
label1 = Label(window, image = photo)
label1.pack()
#update image
def update(ind):
imagefile = filelist[ind]
im = ImageTk.PhotoImage(Image.open(imagefile))
if ind < len(filelist):
ind += 1
else:
ind = 0
label1.configure(image=im)
window.after(2000, update, ind)
window.after(2000, update, 0)
#run the main loop
window.mainloop()
the other code I am trying to combine
1:the one that shows image
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
imagefile = "image.jpg"
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
print('hi')
2:updates gif
from tkinter import *
#change dir
import os
os.chdir("C:/Users/user/Desktop/Learn Python")
#add delay
import time
##### main:
window = Tk()
##### My Photo
photo1 = [PhotoImage(file="anime.gif", format="gif -index %i" %(i)) for i in range(85)]
#update image
def update(ind):
frame = photo1[ind]
if ind < 84:
ind += 1
else:
ind = 0
label.configure(image=frame)
window.after(80, update, ind)
label = Label(window, bg="black")
label.pack()
window.after(0, update, 0)
#####run the main loop
window.mainloop()
I expect it to show all images in the file one by one
it instead shows only the first image, then the window goes blank
You have problem because there is bug in PhotoImage. If you create it in function and assign to local variable then Garbage Collector removes image from memory and you see empty image. You have to create PhotoImages outside function or you have to assign it to some global variable.
Popular solution is to assign it to label which will display it.
label.im = im
Function:
def update(ind):
imagefile = filelist[ind]
im = ImageTk.PhotoImage(Image.open(imagefile))
if ind < len(filelist):
ind += 1
else:
ind = 0
label1.configure(image=im)
label1.im = im # <-- solution
window.after(2000, update, ind)
Doc: PhotoImage

Python Tkinter show image acessed on a listbox

I'm trying to make a python script that shows a image that is acessed on a listbox. This code that I got on the internet works:
import Tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
path = 'img\\2015722_univ_sqs_sm.jpg'
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
window.mainloop()
But when I tried to adapt it do the listbox it stopped working.
from Tkinter import *
from PIL import ImageTk, Image
import glob
files = glob.glob('img\\*.jpg')
class App:
def __init__(self, root):
self.l = Listbox(root, width = 50, height = 15)
self.l.pack()
self.l.bind('<<ListboxSelect>>', self.lol)
self.c = Label(root)
self.c.pack()
for f in files:
self.l.insert(END, f)
def lol(self, evt):
path = files[self.l.curselection()[0]]
img = ImageTk.PhotoImage(Image.open(path))
self.c.image = img
self.c.pack()
root = Tk()
App(root)
root.mainloop()
What am I missing?
You must use the configure method of the label, and store a reference to the image somewhere.
self.c.image = img # save reference
self.c.configure(image=img) # configure the label

Adding a background image in python

I'm trying to add a background image to a canvas in Python. So far the code looks like this:
from Tkinter import *
from PIL import ImageTk,Image
... other stuffs
root=Tk()
canvasWidth=600
canvasHeight=400
self.canvas=Canvas(root,width=canvasWidth,height=canvasHeight)
backgroundImage=root.PhotoImage("D:\Documents\Background.png")
backgroundLabel=root.Label(parent,image=backgroundImage)
backgroundLabel.place(x=0,y=0,relWidth=1,relHeight=1)
self.canvas.pack()
root.mainloop()
It's returning an AttributeError: PhotoImage
PhotoImage is not an attribute of the Tk() instances (root). It is a class from Tkinter.
So, you must use:
backgroundImage = PhotoImage("D:\Documents\Background.gif")
Beware also Label is a class from Tkinter...
Edit:
Unfortunately, Tkinter.PhotoImage only works with gif files (and PPM).
If you need to read png files you can use the PhotoImage (yes, same name) class in the ImageTk module from PIL.
So that, this will put your png image in the canvas:
from Tkinter import *
from PIL import ImageTk
canvas = Canvas(width = 200, height = 200, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)
image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
canvas.create_image(10, 10, image = image, anchor = NW)
mainloop()
just change to :
image = Image.open("~~~path.png")
backgroundImage=ImageTk.PhotoImage(image)
believe me this will 100% work
from Tkinter import *
from PIL import ImageTk
canvas = Canvas(width = 200, height = 200, bg = 'blue')
canvas.pack(expand = YES, fill = BOTH)
image = ImageTk.PhotoImage(file = "C:/Python27/programas/zimages/gato.png")
canvas.create_image(10, 10, image = image, anchor = NW)
mainloop()
You are using root to Attribute PhotoImage this is impossible!
root is your window Tk() class so you cant Attribute it for PhotoImage because it's dosen't have it so you see AttributeError tkinter.Tk() and tkinter.PhotoImage is a different classes. and the same with tkinter.Label.
your code will not working with root.PhotoImage and root.Label.
try to PhotoImage and Label directly.
to create a Label:
backgroundlabel = Label(parent, image=img)
if use any types of png or jpg and jpeg you can't draw it with just PhotoImage you will need PIL library
pip3 install PIL
when you have it use it like:
from PIL import Image, ImageTk # import image so you can append the path and imagetk so you can convert it as PhotoImage
now get your full path image like:
C:/.../img.png
Now use it :
path = "C:/.../img.png" # Get the image full path
load = Image.open(path) # load that path
img = ImageTk.PhotoImage(load) # convert the load to PhotoImage
now you have your code work.
full code:
from Tkinter import *
from PIL import ImageTk,Image
... other stuffs
root = Tk()
canvasWidth = 600
canvasHeight = 400
self.canvas = Canvas(root,width=canvasWidth,height=canvasHeight)
path = "D:\Documents\Background.png" # Get the image full path
load = Image.open(path) # load that path
img = ImageTk.PhotoImage(load)
backgroundLabel = Label(parent,image=img)
backgroundLabel .place(x=0,y=0,relWidth=1,relHeight=1)
self.canvas .pack()
root .mainloop()
Hope this will helpfull.

Categories