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
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 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
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
please help to understand the cause of the phenomenon.
This script does not work (can not see images).
import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage
DIR_IMGS = 'imgs'
imgfiles = os.listdir(DIR_IMGS)
main = Tk()
for imgfile in imgfiles:
win = Toplevel()
imgpath = os.path.join(DIR_IMGS, imgfile)
objImg = PhotoImage(file=imgpath)
Label(win, image=objImg).pack()
main.mainloop()
and this script works (see images).
import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage
imgdir = 'images'
imgfiles = os.listdir(imgdir)
main = Tk()
savephotos = [] #?????????????????????
for imgfile in imgfiles:
imgpath = os.path.join(imgdir, imgfile)
win = Toplevel()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath)
Button(win, image=imgobj).pack()
savephotos.append(imgobj) #?????????????????????
main.mainloop()
they differ only in two rows. it is unclear why such great importance "savephotos"
As FabienAndre writes in the second comment. The garbage collector deletes the image object. The image must be retained for the duration of the display.
I tried a simple code modification:
import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage
DIR_IMGS = 'imgs'
imgfiles = os.listdir(DIR_IMGS)
main = Tk()
objImgList = []
for imgfile in imgfiles:
win = Toplevel()
imgpath = os.path.join(DIR_IMGS, imgfile)
objImg = PhotoImage(file=imgpath)
Label(win, image=objImg).pack()
objImgList.append(objImg)
main.mainloop()
All pictures are now displayed.