86 lines
2.8 KiB
Python
86 lines
2.8 KiB
Python
|
import random
|
||
|
from tkinter import *
|
||
|
from PIL import ImageTk, Image
|
||
|
|
||
|
|
||
|
class ImageWindow:
|
||
|
def __init__(self, window):
|
||
|
self.window = Toplevel(window)
|
||
|
self.window.title("Image")
|
||
|
self.window.geometry("1280x1024")
|
||
|
self.images = []
|
||
|
self.timer = 0
|
||
|
self.timer_label = None
|
||
|
self.timer_check = None
|
||
|
|
||
|
@staticmethod
|
||
|
def maintain_aspect_ratio(event, aspect_ratio):
|
||
|
new_width = event.width
|
||
|
new_height = event.height
|
||
|
|
||
|
new_aspect_ratio = new_width / new_height
|
||
|
|
||
|
# Decide which dimension controls.
|
||
|
if new_aspect_ratio > aspect_ratio:
|
||
|
# Use width as the controlling dimension.
|
||
|
desired_width = new_width
|
||
|
desired_height = int(new_width / aspect_ratio)
|
||
|
else:
|
||
|
# Use height as the controlling dimension.
|
||
|
desired_height = new_height
|
||
|
desired_width = int(new_height * aspect_ratio)
|
||
|
|
||
|
event.widget.resize(f'{desired_width}x{desired_height}')
|
||
|
# Override if necessary.
|
||
|
# if new_width != desired_width or new_height != desired_height:
|
||
|
# # Manually give it the proper dimensions.
|
||
|
# return "break" # Block further processing of this event.
|
||
|
|
||
|
def update_timer(self, current):
|
||
|
current -= 1
|
||
|
if current > 0:
|
||
|
self.timer_label.configure(text=current)
|
||
|
self.timer_check = self.window.after(1000, self.update_timer, current)
|
||
|
else:
|
||
|
self.window.after_cancel(self.timer_check)
|
||
|
|
||
|
def lets_draw(self, images, timer):
|
||
|
self.images = images
|
||
|
self.timer = timer
|
||
|
|
||
|
canvas = Canvas(self.window)
|
||
|
canvas.pack(fill=BOTH, expand=1)
|
||
|
|
||
|
self.timer_label = Label(self.window, text="")
|
||
|
self.timer_label.pack(side=BOTTOM)
|
||
|
|
||
|
random.shuffle(self.images)
|
||
|
|
||
|
image_timer = timer
|
||
|
|
||
|
self.display_new_image()
|
||
|
timer_check = self.window.after(1000, self.update_timer, image_timer)
|
||
|
|
||
|
def display_new_image(self):
|
||
|
ma = self.window.winfo_toplevel()
|
||
|
w, h = ma.winfo_width(), ma.winfo_height()
|
||
|
|
||
|
image_path = self.images[0]
|
||
|
self.images.pop(0)
|
||
|
image = Image.open(image_path)
|
||
|
|
||
|
if image.size[0] > w or image.size[1] > h:
|
||
|
if w < 3 or h < 3: # too small
|
||
|
return # do nothing
|
||
|
image.thumbnail((w - 2, h - 2), Image.ANTIALIAS)
|
||
|
print("resized: win %s >= img %s", (w, h), image.size)
|
||
|
|
||
|
image_to_display = ImageTk.PhotoImage(image)
|
||
|
|
||
|
image_label = Label(self.window, image=image_to_display)
|
||
|
# image_label.bind('<Configure>', lambda event: self.maintain_aspect_ratio(event, 1280 / 1024))
|
||
|
image_label.image = image_to_display
|
||
|
image_label.pack(side="top", fill="both", expand=1)
|
||
|
# Position image
|
||
|
# image_label.place(x=0, y=0)
|