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

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.

Related

displaying an Image in python within a function [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 2 years ago.
I'm trying to display the image from the link the code below works and shows image as intended
from tkinter import *
from PIL import ImageTk,Image
import requests
from io import BytesIO
root = Tk()
root.title('Weather')
root.iconbitmap('icon.ico')
root.geometry("450x300")
image_link = requests.get('https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0006_mist.png')
my_img = ImageTk.PhotoImage(Image.open(BytesIO(image_link.content)))
image_link =Label(root, image = my_img)
image_link.grid(row = 0, column = 0 )
root.mainloop()
but now i have to update my code a little bit and have to put this in a function
from tkinter import *
from PIL import ImageTk,Image
import requests
from io import BytesIO
root = Tk()
root.title('Weather')
root.iconbitmap('icon.ico')
root.geometry("450x300")
def image_func():
image_link = requests.get('https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0006_mist.png')
my_img = ImageTk.PhotoImage(Image.open(BytesIO(image_link.content)))
image_label =Label(root, image = my_img)
image_label.grid(row = 0, column = 0 )
image_func()
root.mainloop()
the above doesn't shows the image so I tried to to put the image label inside a frame but that just shows the frame with nothing inside also the powershell or cmd doesn't show any error
All the objects you create inside the function are local. So these object are deleted when the function exits. You need a way to keep these object existing. For example by using global variables
from tkinter import *
from PIL import ImageTk,Image
import requests
from io import BytesIO
root = Tk()
root.title('Weather')
root.iconbitmap('icon.ico')
root.geometry("450x300")
my_img = None
image_label = None
def image_func():
global my_img, image_label
image_link = requests.get('https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0006_mist.png')
my_img = ImageTk.PhotoImage(Image.open(BytesIO(image_link.content)))
image_label = Label(root, image = my_img)
image_label.grid(row = 0, column = 0 )
image_func()
root.mainloop()
Another way could be returning the objects from the function and keep the returned values
from tkinter import *
from PIL import ImageTk, Image
import requests
from io import BytesIO
root = Tk()
root.title('Weather')
root.iconbitmap('icon.ico')
root.geometry("450x300")
def image_func():
image_link = requests.get('https://assets.weatherstack.com/images/wsymbols01_png_64/wsymbol_0006_mist.png')
my_img = ImageTk.PhotoImage(Image.open(BytesIO(image_link.content)))
image_label = Label(root, image=my_img)
image_label.grid(row=0, column=0)
return my_img, image_label
my_img, image_label = image_func()
root.mainloop()

Display image in tkinter

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

Python 3 tkinter | Image from URL not displaying [duplicate]

This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 3 years ago.
First of all, my code is based on this StackOverflow answer.
Due to circumstance, I am trying to have most of the code packed into a function that I call ImgFromUrl()
import io
import tkinter as tk
import urllib.request
from PIL import Image, ImageTk
def ImgFromUrl(root, url):
with urllib.request.urlopen(url) as connection:
raw_data = connection.read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
return tk.Label(root, image=image)
root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"
widget = ImgFromUrl(root,url)
widget.grid(row=0,column=0)
root.mainloop()
And for some reason, the image does not show up (though the Tkinter window was automatically resized to the size of the image).
However, this works:
# same imports
root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"
with urllib.request.urlopen(url) as connection:
raw_data = connection.read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
widget = tk.Label(root, image=image)
widget.grid(row=0,column=0)
root.mainloop()
So your issue is because image is deleted as soon as the function end and tkinter needs the image to be saved for a reference somewhere.
We can do this with global or by returning the image to a variable defined in the global.
Option 1 global:
import tkinter as tk
import urllib.request
from PIL import Image, ImageTk
import io
def ImgFromUrl(url):
global image
with urllib.request.urlopen(url) as connection:
raw_data = connection.read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
return image
root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"
widget = tk.Label(root, image=ImgFromUrl(url))
widget.grid(row=0, column=0)
root.mainloop()
Option 2 returning the image object to a variable defined in the global namespace:
import tkinter as tk
import urllib.request
from PIL import Image, ImageTk
import io
def ImgFromUrl(url):
with urllib.request.urlopen(url) as connection:
raw_data = connection.read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
return image
root = tk.Tk()
url = "http://imgs.xkcd.com/comics/python.png"
image = ImgFromUrl(url)
widget = tk.Label(root, image=image)
widget.grid(row=0, column=0)
root.mainloop()

Display an image tkinter macOSX [duplicate]

How do I insert a JPEG image into a Python 2.7 Tkinter window? What is wrong with the following code? The image is called Aaron.jpg.
#!/usr/bin/python
import Image
import Tkinter
window = Tkinter.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
imageFile = "Aaron.jpg"
window.im1 = Image.open(imageFile)
raw_input()
window.mainloop()
Try this:
import tkinter as tk
from PIL import ImageTk, Image
#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')
path = "Aaron.jpg"
#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))
#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)
#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")
#Start the GUI
window.mainloop()
Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 = ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()
from tkinter import *
from PIL import ImageTk, Image
window = Tk()
window.geometry("1000x300")
path = "1.jpg"
image = PhotoImage(Image.open(path))
panel = Label(window, image = image)
panel.pack()
window.mainloop()

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

Categories