HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Flipbook type animation with Tkinter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
animationwithtkintertypeflipbook

Problem

I am writing a program in Python that takes a folder of images and animates them.

For example, going through a list of pictures like this and animating them one by one:

Relevant features include:

-
Upon startup, ask user what directory they want to animate images from.

-
If the chosen directory has no valid images, display an error message that describes the error, shows the user a list of valid file types, and then re-asks for a directory.

-
Using up and down arrow keys speeds and slows the frame rate.

-
The window starts out at default size, but the user can make the window bigger or smaller with his/her mouse. Then, when the user refreshes (presses Enter), the images will be scaled to fit the window size he/she has chosen. Images will always keep their aspect ratio.

-
Image files are sorted numerically and alphabetically for the animation. i.e.

['hello.ico', '10.png', '2.jpg']


becomes

['2.jpg', '10.png', 'hello.ico']


I know the code works in Python 2.7, but I haven't tried it in Python 3. It should work, I think!

Any comments, improvements, or suggestions?

```
# -- coding: utf-8 --
"""
Flipbook Animation: Animate a folder of images.

All image names that are numbers will be sorted in
increasing order, the rest will be sorted alphabetically.
For example, files:
"70.png", "image.jpg", "29.bmp", and "8.ico"
will be animated in the following order:
"8.ico", "29.bmp", "70.png", "image.jpg".

Image types must be in VALID_TYPES (defined below).

Up/Down arrow key increases/decreases the frame rate.
Enter (Return) key refreshes the animation.

Images will be scaled to fit the screen size while
keeping their original aspect ratios. Therefore, to
resize the images, simply resize the window with the
mouse and press Enter (Return) to refresh.
"""

import io, os
from PIL import Image, ImageTk

if os.sys.version_info.major > 2:
from tkinter.filedialog import askdirectory
import tkinter as tk
else:
from tkFileDialog imp

Solution

Your sorting is overcomplicated as you re-invent a sorting algoritmh in your code while Python has it built-in.

You should use the standard list.sort function and give it an appropriate key (credit to Mathias for suggesting this as it works in-place). "If the name starts with a digit sort by the integer value of the starting number else sort alphabetically".

Context

StackExchange Code Review Q#138404, answer score: 3

Revisions (0)

No revisions yet.