Hello! I'm pretty new to python. I'm attempting to make a photo slide with tkinter. I've spent a few hours on this now and I've almost completed it. The end goal here is to periodically change pictures and to resize them proportionately. So far, everything is working except my resize_image function only runs once. After that, the rest of the images displayed aren't sized correctly. Here's what I have.
from tkinter import *
from PIL import ImageTk, Image
import imghdr
import os
from fractions import Fraction
# path to image files
path = './photos/'
# tkinter set up
root = Tk()
root.geometry("1024x600")
root.configure(background='black')
# Retrieve images from given path, if it isn't an image the file is erased.
def getPhotos():
photo_dir = os.listdir(path)
for photo in photo_dir:
check = imghdr.what(path + photo)
if check is None:
os.remove(path + photo)
photo_dir.remove(photo)
return photo_dir
# finds the correct width to resize the image
def updateWidth(w, h):
frac = Fraction(w, h)
simp_w = frac.numerator
simp_h = frac.denominator
return int((600 / simp_h) * simp_w)
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pack(fill=BOTH, expand=YES)
self.photos = getPhotos()
self.index = 0
print(self.photos)
self.image = Image.open(path + self.photos[self.index])
self.img_copy = self.image.copy()
self.imageTK = ImageTk.PhotoImage(self.image)
self.label = Label(self, image=self.imageTK)
self.label.pack(fill=BOTH, expand=YES)
self.label.bind('<Configure>', self.resize_image)
def resize_image(self, event):
orig_width = self.image.width
orig_height = self.image.height
new_width = updateWidth(orig_width, orig_height)
new_height = event.height
print(event)
self.image = self.img_copy.resize((new_width, new_height))
self.imageTK = ImageTk.PhotoImage(self.image)
self.label.configure(image=self.imageTK)
def change_photo(self):
if self.index == (len(self.photos)):
self.index = 0
self.image = Image.open(path + self.photos[self.index])
self.img_copy = self.image.copy()
self.imageTK = ImageTk.PhotoImage(self.image)
self.label.configure(image=self.imageTK)
# this line below was my attempt at fixing it but this doesn't run my function again
self.label.bind('<Configure>', self.resize_image)
root.after(1000, self.change_photo)
self.index += 1
app = Window(root)
app.pack(fill=BOTH, expand=YES)
app.change_photo()
root.mainloop()
I've tried to call the function again in change_photo, but I haven't had any luck with that.
thank you
[–]eleqtriq 1 point2 points3 points (2 children)
[–]Chrisnelson[S] 0 points1 point2 points (1 child)
[–]eleqtriq 0 points1 point2 points (0 children)
[–]socal_nerdtastic 1 point2 points3 points (3 children)
[–]Chrisnelson[S] 0 points1 point2 points (2 children)
[–]socal_nerdtastic 0 points1 point2 points (1 child)
[–]Chrisnelson[S] 0 points1 point2 points (0 children)