python tkinter show images in a directory - python

I have a folder which has some images. I want to display all the images using tkinter in a single window. Also whenever I click any image displayed in the window, I need to display the path of the image. I tried using for loop but it prints all the image file path. Here is the code I tried,
from Tkinter import *
import os
from PIL import ImageTk, Image
def getFileName(image):
print str(image)
gtk = Tk()
def showImages(folder):
for images in os.listdir(os.getcwd()):
if images.endswith("png"):
im = Image.open(images)
tkimage = ImageTk.PhotoImage(im)
imageButton = Button(gtk, image=tkimage, command=getFileName(images)
imageButton.image=tkimage
imageButton.pack()
gtk.mainloop()
Can anyone say what I'm doing wrong?

for images in os.listdir(os.getcwd()):
if images.endswith("png"):
im = Image.open(images)
tkimage = ImageTk.PhotoImage(im)
handler = lambda img = images: getFileName(img) #here modify
imageButton = Button(gtk, image=tkimage, command=handler)#here
imageButton.image=tkimage
imageButton.pack()
Because button-press callbacks are run with no arguments, if we
need to pass extra datato the handler, it must be wrapped in an object
that remembers that extra data and passes it along, by deferring the
call to the actual handler. Here, a button press runs the function
generated by the lambda, an indirect call layer that retains
information from the enclosing scope. The net effect is that the real
handler.
-- << Programming Python>> page 435

Related

How to open an image in Python and close afterwards?

Python Versions: 3.7.9
I've tried using Pillow/PIL with show() and close() however that just closes the command prompt and leaves the file viewer still open.
I've tried subprocess Popen but that just gives me the error 'The system cannot find the file specified' even though the file is correct. So I'm just stuck right now. I figured this would've been a simple process for Python.
I'm just trying to open an image and then after the user clicks a button, be able to close it.
Open to suggestions/libraries. Thanks!
Just call this function and a new window will pop up with the image.
Your code wont be executed until the window is closed.
import tkinter
from PIL import ImageTk, Image
def image_preview (path, size = (0, 0)):
root = tkinter.Tk ()#Start window
root.title ("Preview")#Modify this to change the title
rawimg = Image.open(path)#Open image path
if size != (0, 0):#If a specific resolution has been requested
rawimg = rawimg.resize (size)#Change the image resolution
img = ImageTk.PhotoImage(rawimg)#Adapt the image to tkinter
panel = tkinter.Label (root, image = img)#Add image to the window
panel.pack ()#Build window
root.mainloop ()#Run window
Example line to use this:
image_preview ("image.png", (500, 500))#With specified resolution
image_preview ("image.png")#Use the image resolution

How to make buttons out of list

I am trying to write a code that will make buttons out of Images. Whenever you click that a button It will display that image.
import os
from PIL import ImageTk, Image
import tkinter
root = tkinter.Tk()
folder_list = os.listdir(r"C:\Users\Teknoloji\Desktop\Phyton\Jack\Selam")
def Imagen():
image = tkinter.Canvas(root,width=300,height=300)
for b in folder_list:
if b == my_text:
img = ImageTk.PhotoImage(Image.open(f"Images\{b}"))
label = tkinter.Label(image=img)
print(my_text)
label.image = img
image.create_image(120,120,image=img)
image.pack()
for i in folder_list:
button = tkinter.Button(root,text=i,command=Imagen)
my_text = button.cget("text")
print(my_text)
button.pack()
root.mainloop()
I have took your code and made some changes here:
import os
from PIL import ImageTk, Image
import tkinter
root = tkinter.Tk()
folder_list = os.listdir(r"C:\Users\Teknoloji\Desktop\Phyton\Jack\Selam")
def Imagen(img_path):
img = ImageTk.PhotoImage(Image.open(f'images/{img_path}'))
#label = tkinter.Label(image=img)
image.whatever = img #keeping a reference, can be anything
image.itemconfigure('image',image=img)
image.pack()
for i in folder_list:
button = tkinter.Button(root,text=i,command=lambda i=i:Imagen(i),width=10)
button.pack(pady=5)
image = tkinter.Canvas(root,width=300,height=300)
image.create_image(120,120,tag='image')
root.mainloop()
What all have I done?
I've removed some unwanted part from your code, like unnecessary looping inside of function and also it seems like your not using your label to display image instead using canvas, either way ive made sure that it does not overwrite the existing image, when you press button.
Also I have passed the image path as a parameter onto the function which opens the image, so that lambda can have a parameter to pass on to the function.
How does the loop button work?
(Taken from here)
This may look magical, but here's what's happening. When you use that lambda to define your function, the open_this call doesn't get the value of the variable i at the time you define the function. Instead, it makes a closure, which is sort of like a note to itself saying "I should look for what the value of the variable i is at the time that I am called". Of course, the function is called after the loop is over, so at that time i will always be equal to the last value from the loop.
Using the i=i trick causes your function to store the current value of i at the time your lambda is defined, instead of waiting to look up the value of i later.
Do let me know if this works.
Do let me know if you have any doubts or error regarding this.
Cheers

Displaying an image in python via Button and Canvas

I am a begginer in python, tkinter. I have written a code that should normally display an image in a canvas.
What happens is that the main frame (gui) is displayed with the menu bar, then when I click on load image, the gui window shrinks (to 100x100 I guess) but nothing is displayed within.
Could you please explain to me why this is happening so I can understand where the error occurs, and how to correct it?
# -*- coding:utf-8 -*-
# Imports
from tkinter import Tk, Menu, Canvas
from PIL import Image, ImageTk
# Function definitions
def deleteImage(canvas):
canvas.delete("all")
return
def loadImage(canvas, img):
filename = ImageTk.PhotoImage(img)
canvas.image = filename
canvas.create_image(0,0,anchor='nw',image=filename)
return
def quitProgram():
gui.destroy()
# Main window
gui = Tk()
# Inside the main gui window
#Creating an object containing an image
# A canvas with borders that adapt to the image within it
img = Image.open("fleur.jpg")
canvas = Canvas(gui,height=img.size[0],width=img.size[0])
canvas.pack()
# Menu bar
menubar = Menu(gui)
# Adding a cascade to the menu bar:
filemenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Files", menu=filemenu)
# Adding a load image button to the cascade menu "File"
filemenu.add_command(label="Load an image", command=loadImage)
# Adding a delete image button to the cascade menu "File"
filemenu.add_command(label="Delete image", command=deleteImage)
filemenu.add_separator()
filemenu.add_command(label="Quit", command=quitProgram)
menubar.add_separator()
menubar.add_cascade(label="?")
# Display the menu bar
gui.config(menu=menubar)
gui.mainloop()
EDIT:
The second problem is that I want to create a canvas and the image in the main gui window, and pass them as arguments to the menu buttons (See code above, where img and canvas are created separately from the function loadImage). Seeing as putting parenthesis in the command=loadImage() created a problem on its own.
Another point that rises a question in my head : Regarding the first problem which was solved by keeping a reference to the filename=ImageTk.PhotoImage(img). Wouldn't it normally be pointless to keep a reference inside the function since it's a local variable anyway?
As stated in effbot's PhotoImage page, you have to keep a reference of your image to ensure it's not garbage collected.
You must keep a reference to the image object in your Python program,
either by storing it in a global variable, or by attaching it to
another object.
Note: When a PhotoImage object is garbage-collected by Python (e.g.
when you return from a function which stored an image in a local
variable), the image is cleared even if it’s being displayed by a
Tkinter widget.
To avoid this, the program must keep an extra reference to the image
object. A simple way to do this is to assign the image to a widget
attribute, like this:
Your loadImage() method should look like below.
def loadImage():
img = Image.open("fleur.jpg")
filename = ImageTk.PhotoImage(img)
canvas = Canvas(gui,height=100,width=100)
canvas.image = filename # <--- keep reference of your image
canvas.create_image(0,0,anchor='nw',image=filename)
canvas.pack()

displaying the selected image using tkinter

I want to know whether I can display an image from the path I have selected? like, I have a path for example: c:\user\desktop\33.jpg, and I want to take only that jpg file and I have to display that image using label or something. If it is possible, I want to know how?
Thanks in advance!
Here is a sample code for what you are asking:
from Tkinter import Label,Tk
from PIL import Image, ImageTk
import tkFileDialog
root = Tk()
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
root.mainloop()
You will be wanting to add a button for calling the askopenfilename because right now its calling it the moment the program begins.
Also you might wanna add more file extensions to filetypes

Python 2.7 How to add images on the canvas with Tkinter

I need to add an image to the canvas. I have tried countless amounts of things, and finally decided to make a question on here.
This is what I have imported
from Tkinter import *
import tkFont
from PIL import ImageTk, Image
And this is the line of code I'm trying to add to import an image from the same folder the main file is in.
c.create_image(100,100, anchor=N, image = ghost.jpg)
I've also tried putting ""s around 'ghost.jpg' and it says the Image does not exist then. Without the quotes it says "global name 'ghost' does not exist."
Can anyone help?
Canvas.create_image's image argument
should be a PhotoImage or BitmapImage, or a
compatible object (such as the PIL's PhotoImage). The application must
keep a reference to the image object.
from Tkinter import *
"""python 2.7 =Tkinter"""
from PIL import Image, ImageTk
app = Tk()
temp=Image.open("photo.jpg")
temp = temp.save("photo.ppm","ppm")
photo = PhotoImage(file = "photo.ppm")
imagepanel=Label(app,image = photo)
imagepanel.grid()
app.mainloop()
This is a bit of code I wrote in python 2.7 with Tkinter and PIL to import a jpg file from a given directory, this doesn't pop up off the screen.
You should replace photo with the file name (and directory) and app with the relevant variable you set.

Categories