I want python to iterate images in a directory and pack that to the GUI
from tkinter import *
from pathlib import Path
from PIL import ImageTk, Image
root = Tk()
images = []
paths = Path("images").glob('**/*.png')
for path in paths:
photo = Image.open(path)
photo.thumbnail((100, 100))
img = ImageTk.PhotoImage(photo)
label = Label(image=img)
images.append(label)
for image in images:
image.pack()
root.mainloop()
But the output is just the last picture on the directory:
here my attempt:
from tkinter import *
from pathlib import Path
from PIL import ImageTk, Image
pippo = Tk()
images = []
paths = Path("images").glob('**/*.png')
for path in paths:
print(path)
photo = Image.open(path)
photo.thumbnail((100, 100))
img = ImageTk.PhotoImage(photo)
images.append(img)
print(images)
for img in images:
label = Label(pippo, image=img)
label.pack(side = 'bottom')
pippo.mainloop()
output starting from three colored circles is:
Related
This is my code for the button that opens an app:
Modules:
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from subprocess import Popen
Importing Image:
path = ("C:\Pictures\GoogleLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
Generic Canvas Button:
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey", height = 6, width = 10)
canvas.create_window(1167,714, window=openCalcWin)
What I have Tried:
I attempted to make the background of the button into an image by using bg or img. But this just creates an tiny image logo that can't be clicked. Indicating that there was an error loading the image, but there was no error code or anything in the IDLE Shell.
There was other attempts of code that I forgot, but most of them ends up the same: no button appeared and no error code.
Edit:
import tkinter as tk
from PIL import ImageTk, Image
from subprocess import Popen
##Application Window:
root=tk.Tk()
root.title("Virtual Desktop")
root.resizable(False, False)
#Determine Window Resolution
canvas = tk.Canvas(root, width=1280, height=780, bg="#263D42")
canvas.pack()
#Importing Calulator Image
path = ("C:\Pictures\CalcLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
#Calculator Button
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey", height = 6, width = 10)
canvas.create_window(1167,714, window=openCalcWin)
The following works for me. The most important change was to specify an image= keyword argument, when creating the Button.
The other thing I noted was the:
path = ("C:\Pictures\CalcLogo.png")
you had. The parentheses are unnecessary (but don't hurt), however you need to add an r prefix to all strings containing back-slash characters like paths on Windows.
path = r"C:\Pictures\CalcLogo.png"
or just use forward-slashes (which work fine on Windows):
path = "C:/Pictures/CalcLogo.png"
Full code:
import tkinter as tk
from PIL import ImageTk, Image
from subprocess import Popen
##Application Window:
root=tk.Tk()
root.title("Virtual Desktop")
root.resizable(False, False)
#Determine Window Resolution
canvas = tk.Canvas(root, width=1280, height=780, bg="#263D42")
canvas.pack()
#Importing Calulator Image
path = "8-ball.png" # My own image.
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
#Calculator Button
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', command=openCalc, bg="Grey",
image=img)
canvas.create_window(1167,714, window=openCalcWin)
root.mainloop()
I found this solution. You can check it learn about it yourself, but basically you do not provide any args when creating the obj/Button, you only provide the root, image and command, and it should work.
Something like this:
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from subprocess import Popen
root = Tk()
path = ("C:\Pictures\GoogleLogo.png")
img = Image.open(path)
img = img.resize((96, 96), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
def openCalc():
Popen("calc.exe")
openCalcWin = tk.Button(text='Calculator', image=img, command=openCalc)
openCalcWin.pack()
root.mainloop()
if you want, you can look at some examples and learn more here - https://www.activestate.com/resources/quick-reads/how-to-add-images-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()
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
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
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.